Skip to content

Query and Style

Style dataclass

Style(*, empty_braces: bool = True, grouping: GroupingPosition = SUFFIX, compact_matchers: bool = False, paren_space: bool = True)

Rendering options for to_string; the defaults reproduce str(query).

Attributes:

Name Type Description
empty_braces bool

Render up{} (True) or a bare up (False). Metric names that are PromQL keywords always keep their braces.

grouping GroupingPosition

Place by/without after (GroupingPosition.SUFFIX, sum(x) by (job)) or before (GroupingPosition.PREFIX, sum by (job) (x)) the aggregation arguments.

compact_matchers bool

Render {job="api"} instead of { job = "api" }.

paren_space bool

Render by (job) (True) or by(job) (False); also applies to on, ignoring, group_left and group_right.

Examples:

>>> up = InstantVector("up", [Label.eq("job", "api")])
>>> expr = sum_(rate(up[Duration(m=5)])).by(["job"])
>>> print(expr.to_string(style=Style.prometheus()))
sum by (job) (rate(up{job="api"}[5m]))

GroupingPosition

Bases: Enum

Where an aggregation's by/without clause is placed.

prometheus classmethod

prometheus() -> Style

Match Prometheus' canonical formatting (sum by (job) (up{job="api"})).

Query

Bases: ABC

Base class for all PromQL query components.

to_string abstractmethod

to_string(indent: str | int | None = None, _indent_level: int = 0, *, style: Style = DEFAULT_STYLE) -> str

Render this expression as a PromQL string.

Parameters:

Name Type Description Default
indent str | int | None

Enables multi-line output: an int is a number of spaces per level, a whitespace str is used verbatim per level. None renders a single line.

None
_indent_level int

Current nesting depth; internal, leave at 0.

0
style Style

Formatting options, see Style.

DEFAULT_STYLE

Raises:

Type Description
ValueError

If indent is a bool or a non-whitespace str.

subquery

subquery(range: SCALAR_TYPE, resolution: SCALAR_TYPE | None = None, *, offset: SCALAR_TYPE | None = None, at: AT_TYPE | None = None) -> Subquery

Evaluate this expression as a subquery: <expr>[range:resolution].

See Subquery; slice syntax expr[range:resolution] is a shorthand for this method.

Parameters:

Name Type Description Default
range SCALAR_TYPE

Window length; raw numbers are seconds (3600 → [1h:]).

required
resolution SCALAR_TYPE | None

Step between evaluations; None uses the global evaluation interval.

None
offset SCALAR_TYPE | None

Time shift; raw numbers are seconds.

None
at AT_TYPE | None

Evaluation time: a Unix timestamp, "start()" or "end()".

None