Generators

All generators live in hegel.generators, conventionally imported as gs:

from hegel import generators as gs

A generator is an immutable description of how to produce values. Building one validates its arguments, so a bad argument raises InvalidArgument where the generator is defined, and the same generator can be drawn from any number of times, in any number of tests.

Numbers and booleans

hegel.generators.integers(min_value: int | None = None, max_value: int | None = None) → Generator[int]

Generate integers in [min_value, max_value], inclusive.

Either bound may be omitted. Python integers are unbounded, but the values drawn are not: a missing bound is taken to be 2**127 values beyond the other bound, or beyond zero when that is further. Values shrink toward zero, or toward the bound nearest zero when zero is out of range.

A bound that is not an integer (a float with an integral value is accepted) or min_value > max_value is an InvalidArgument.

n = tc.draw(gs.integers(min_value=0, max_value=100))
hegel.generators.floats(min_value: float | None = None, max_value: float | None = None, *, allow_nan: bool | None = None, allow_infinity: bool | None = None, allow_subnormal: bool | None = None, width: int = 64, min_value_exclusive: float | None = None, max_value_exclusive: float | None = None) → Generator[float]

Generate floating-point numbers in [min_value, max_value].

Either bound may be omitted. min_value_exclusive and max_value_exclusive set a bound that is itself excluded, in place of the inclusive min_value and max_value; giving both forms of one bound is an InvalidArgument. Values shrink toward 0.0, and toward simple values with few significant digits: integers before fractions.

allow_nan, allow_infinity and allow_subnormal default to whatever the bounds permit. Without bounds, NaN and the infinities are allowed. Setting a bound disables NaN, and asking for it with a bound is an InvalidArgument. Setting both bounds disables infinity; with one bound, the infinity on the unbounded side is allowed unless allow_infinity=False. Subnormals are allowed when the range contains any.

width is 64 (the default) or 32, in which case every value is exactly representable as a 32-bit float and the bounds must be too.

Bounds that are NaN or not real numbers, min_value > max_value, and any combination that leaves no values (allow_infinity=False with min_value=math.inf, or min_value_exclusive=1.0 with max_value=1.0, say) are each an InvalidArgument.

probability = tc.draw(gs.floats(min_value=0.0, max_value=1.0))
positive = tc.draw(gs.floats(min_value_exclusive=0.0))
finite = tc.draw(gs.floats(allow_nan=False, allow_infinity=False))
hegel.generators.booleans() → Generator[bool]

Generate True or False, shrinking toward False.

Text and bytes

hegel.generators.text(alphabet: Any = None, *, min_size: int = 0, max_size: int | None = None, codec: str | None = None, min_codepoint: int | None = None, max_codepoint: int | None = None, categories: Iterable[str] | None = None, exclude_categories: Iterable[str] | None = None, include_characters: Iterable[str] | None = None, exclude_characters: Iterable[str] | None = None) → Generator[str]

Generate Unicode strings of between min_size and max_size characters, shrinking toward shorter strings of simpler characters ("", then "0").

Without max_size the engine applies its default maximum for text: 100 characters, or min_size + 100 when min_size is larger than that, whatever the alphabet. A negative size or max_size < min_size is an InvalidArgument.

alphabet restricts the characters: a string or sequence of characters, or a characters() generator. Any other generator is an InvalidArgument; to build text from an arbitrary generator of characters, draw a list of them and join it: gs.lists(chars).map("".join). An empty alphabet gives only "". The keyword filters (codec, codepoint bounds, Unicode categories, included and excluded characters) are shorthand for a characters() alphabet, with the same meanings, and cannot be combined with alphabet. Surrogate code points are never generated unless asked for by category.

Unicode categories follow the Unicode version of the running Python’s unicodedata, so str.isalpha and friends agree with them.

name = tc.draw(gs.text(min_size=1))
word = tc.draw(gs.text(alphabet="abc", max_size=5))
ascii_text = tc.draw(gs.text(codec="ascii"))
hegel.generators.characters(*, codec: str | None = None, min_codepoint: int | None = None, max_codepoint: int | None = None, categories: Iterable[str] | None = None, exclude_categories: Iterable[str] | None = None, include_characters: Iterable[str] | None = None, exclude_characters: Iterable[str] | None = None) → Generator[str]

Generate single characters (strings of length one), shrinking toward "0".

Each argument narrows the characters generated:

  • codec: only characters that the codec can encode. One of "ascii", "latin-1" (or "iso-8859-1") and "utf-8".

  • min_codepoint, max_codepoint: an inclusive range of code points, within 0 to 0x10FFFF.

  • categories: only these Unicode general categories, by two-letter name ("Lu") or by major class ("L" for every letter).

  • exclude_categories: every category but these. Surrogates ("Cs") are always excluded unless categories names them.

  • include_characters: characters to allow whatever the other filters say.

  • exclude_characters: characters never to generate.

categories and exclude_categories cannot both be given. An unknown codec or category, an out-of-range code point, or max_codepoint < min_codepoint is an InvalidArgument. Categories follow the Unicode version of the running Python’s unicodedata.

upper = tc.draw(gs.characters(categories=["Lu"]))
printable_ascii = tc.draw(gs.characters(min_codepoint=32, max_codepoint=126))
hegel.generators.from_regex(regex: Any, *, fullmatch: bool = True, alphabet: Any = None) → Generator[str]

Generate strings matching regex, a pattern string or a compiled re.Pattern (whose flags are honoured).

By default the whole string matches, as re.fullmatch() checks; with fullmatch=False the string merely contains a match, as re.search() would find, and may have arbitrary text around it. (Hypothesis’s from_regex defaults to fullmatch=False.)

alphabet restricts the characters the pattern’s character classes and . may produce, as a string of characters or a characters() generator; it cannot be empty, and cannot be used with a bytes pattern. A bytes pattern generates bytes, matching with the semantics of re for bytes (\w and friends are ASCII-only).

The pattern is parsed and the strings generated by Hegel’s engine, not by re. A pattern the engine cannot parse, or one that can match nothing over its alphabet, is an InvalidArgument when the generator is built.

identifier = tc.draw(gs.from_regex(r"[a-z_][a-z0-9_]*"))
hegel.generators.from_lark(grammar: str, *, start: str | None = None, explicit: Mapping[str, Generator[str]] | None = None, alphabet: Any = None, max_size: int | None = None, max_depth: int | None = None, import_path: str | PathLike[str] | None = None) → Generator[str]

Generate strings matching grammar, a grammar written in the syntax of the Lark parsing library, starting from its start rule (or the rule named by start).

The whole grammar language is supported: rules, terminals with string and regex patterns and priorities, %import (including Lark’s bundled common, python, unicode and lark grammars), %ignore, %declare, %override, %extend and templates. Generated strings are ones Lark’s Earley parser accepts for the grammar, with %ignored terminals such as whitespace and comments inserted wherever a lexer would skip them; a string Lark’s basic lexer would read differently is avoided where the grammar allows it. A draw that cannot produce such a string after several attempts rejects the test case, as a failed assume() does. The grammar is parsed and the strings generated by Hegel’s engine: Lark itself need not be installed.

explicit maps terminal names to generators of strings, which supply those terminals’ values instead of their patterns. A terminal the grammar %declares without defining needs one; any other may be overridden. The values are beyond the lexing checks made on the rest of the string: it is the generator’s part to draw values that read as the terminal where they land (a value under a quoted-string terminal should contain no quote, say). A value that is not a string is an InvalidArgument when drawn.

alphabet restricts the characters the terminals’ patterns may produce, as for from_regex(): a string of characters or a characters() generator.

max_size caps the length of a string in characters, explicit terminals’ values included (default 8192, at most 1048576); a string whose values push it over is drawn again with less room for the grammar’s own text. max_depth caps how deeply rules nest (default 200, at most 500). import_path is the directory %imported grammars are read from: %import a.b.X reads a/b.lark from it, and Lark’s bundled grammars stand in when it has no such file. A relative import (%import .lib.X) in a/b.lark reads a/lib.lark, and in grammar itself lib.lark.

A grammar Lark would reject, an undefined start rule, a cap below the smallest string the grammar can produce, or an explicit generator for a terminal the grammar does not have is an InvalidArgument when the generator is built.

EXPRESSIONS = r'''
    ?start: sum
    ?sum: product | sum "+" product
    ?product: atom | product "*" atom
    ?atom: NUMBER | "(" sum ")"
    %import common.NUMBER
    %import common.WS
    %ignore WS
'''

expression = tc.draw(gs.from_lark(EXPRESSIONS))
hegel.generators.binary(*, min_size: int = 0, max_size: int | None = None) → Generator[bytes]

Generate byte strings of between min_size and max_size bytes, shrinking toward shorter strings of zero bytes.

Without max_size the engine applies its default maximum: 100 bytes, or min_size + 100 when min_size is larger than that. A negative size or max_size < min_size is an InvalidArgument.

Collections

hegel.generators.lists(elements: Generator[T], *, min_size: int = 0, max_size: int | None = None, unique: bool = False, unique_by: Any = None) → Generator[list[T]]

Generate lists of values from elements, with between min_size and max_size elements.

max_size defaults to no fixed limit: the engine decides when to stop, and keeps lists reasonably short. Lists shrink toward fewer elements, and each element shrinks as elements does.

unique=True requires the elements to be distinct (and hashable). unique_by is a key function, or a tuple of them, each of whose results must be distinct across the list; it cannot be combined with unique. A duplicate element is discarded and another drawn in its place. When the elements are a sampled_from() (under any map() and filter()), unique lists draw its elements without replacement, so a unique list needing most of them is still found quickly.

A negative size, max_size < min_size, or a min_size larger than the number of distinct values elements is known to have, is an InvalidArgument.

xs = tc.draw(gs.lists(gs.integers(), min_size=1, max_size=10))
ids = tc.draw(gs.lists(gs.integers(), unique=True))
pairs = tc.draw(gs.lists(gs.tuples(gs.text(), gs.integers()), unique_by=lambda p: p[0]))
hegel.generators.sets(elements: Generator[T], *, min_size: int = 0, max_size: int | None = None) → Generator[set[T]]

Generate sets of values from elements, with between min_size and max_size members; the elements must be hashable. Sizes are as for lists(), and a drawn duplicate is discarded and another element drawn in its place.

hegel.generators.frozensets(elements: Generator[T], *, min_size: int = 0, max_size: int | None = None) → Generator[frozenset[T]]

Generate frozensets of values from elements, as sets() does.

hegel.generators.dicts(keys: Generator[Any], values: Generator[Any], *, min_size: int = 0, max_size: int | None = None) → Generator[dict[Any, Any]]

Generate dicts with keys drawn from keys and values from values, with between min_size and max_size entries.

Sizes are as for lists(). A drawn duplicate key is discarded and another drawn in its place. For dicts with a fixed set of keys, use fixed_dicts().

scores = tc.draw(gs.dicts(gs.text(), gs.integers(0, 100)))
hegel.generators.fixed_dicts(mapping: dict[Any, Generator[Any]], *, optional: dict[Any, Generator[Any]] | None = None) → Generator[dict[Any, Any]]

Generate dicts with the keys of mapping, each value drawn from the generator that mapping gives for its key.

Each key of optional (a dict of the same shape) is present or absent independently, shrinking toward absent. A key in both, or a value that is not a generator, is an InvalidArgument. The keys appear in the order given, required keys first.

user = tc.draw(gs.fixed_dicts(
    {"name": gs.text(), "age": gs.integers(0, 120)},
    optional={"email": gs.emails()},
))
hegel.generators.tuples(*generators: Generator[Any]) → Generator[tuple[Any, ...]]

Generate tuples with one element from each generator, in order: tuples(gs.integers(), gs.text()) generates pairs like (0, ""). With no generators it generates only ().

hegel.generators.iterables(elements: Generator[T], *, min_size: int = 0, max_size: int | None = None, unique: bool = False, unique_by: Any = None) → Generator[Iterable[T]]

Generate one-shot iterables of values from elements: an iterator over a list that lists() would generate, with the same arguments. Iterating once exhausts it, which tests code that must not iterate its input twice. The failure report prints the values it started with.

Choosing from values

hegel.generators.sampled_from(elements: Any) → Generator[Any]

Pick one of elements, shrinking toward the first.

elements is a sequence (copied if mutable, so later changes to it do not affect the generator), any other iterable (read once), or an Enum class, whose members are sampled in definition order. A Flag class also yields the empty flag and combinations of its members. An empty collection, an enum with no members, or a set (which has no stable order to shrink in) is an InvalidArgument.

colour = tc.draw(gs.sampled_from(["red", "green", "blue"]))

.filter on the result narrows the elements rather than retrying draws, so even a predicate that accepts one element in thousands finds it.

hegel.generators.just(value: T) → Generator[T]

Always generate value.

The same object is returned by every draw, so mutating it in one test case is visible in the next. It is useful as an argument to one_of() or builds(), or as the result of a flat_map().

hegel.generators.none() → Generator[None]

Always generate None. The same as just(None).

hegel.generators.nothing() → Generator[Any]

A generator with no values: every draw rejects the test case, as TestCase.reject does.

one_of() drops it, so one_of(gs.nothing(), g) is g.

hegel.generators.permutations(elements: Iterable[T]) → Generator[list[T]]

Generate reorderings of elements (any iterable, read once), as lists, shrinking toward the original order.

hegel.generators.samples(elements: Iterable[T], *, min_size: int = 0, max_size: int | None = None, replacement: bool = True) → Generator[list[T]]

Generate lists sampled from elements, with between min_size and max_size items.

With replacement=True (the default) each item is chosen independently, so an element may appear more than once. With replacement=False each element is used at most once, in the order drawn, so the size is capped at len(elements). A min_size that cannot be met is an InvalidArgument when drawn.

hegel.generators.subsequences(elements: Iterable[T], *, min_size: int = 0, max_size: int | None = None) → Generator[list[T]]

Generate subsequences of elements: lists of some of its elements, each used at most once, in their original order. Sizes are as for lists(), capped at len(elements); a min_size larger than that is an InvalidArgument when drawn.

Combining generators

hegel.generators.one_of(*generators: Any) → Generator[Any]

Draw from one of generators, shrinking toward the earlier ones.

The generators are passed as separate arguments or as one iterable; a | b is one_of(a, b). Nested one_of calls are flattened, nothing() arguments are dropped, and a single generator is returned as it is. one_of() with no arguments, or an argument that is not a generator, is an InvalidArgument.

key = tc.draw(gs.one_of(gs.integers(), gs.text()))
key = tc.draw(gs.integers() | gs.text())
hegel.generators.optional(inner: Generator[T]) → Generator[T | None]

Generate either None or a value from inner, shrinking toward None. Passing something other than a generator is an InvalidArgument.

hegel.generators.composite(function: Callable[[...], T]) → Callable[[...], Generator[T]]

Define a generator as a function taking a TestCase first.

Calling the decorated function with the remaining arguments returns a generator; each draw runs the function body with the test case and those arguments, and the generated value is what the body returns. The body draws with tc.draw like a test does, so later draws can depend on earlier ones. Its own draws are not printed separately: the failure report prints the composite’s value.

@hegel.composite
def sorted_pairs(tc, limit):
    a = tc.draw(gs.integers(0, limit))
    b = tc.draw(gs.integers(a, limit))
    return (a, b)

@hegel.test
def test_pairs(tc):
    a, b = tc.draw(sorted_pairs(100))
    assert a <= b

Decorating a class, or a function without a positional first parameter for the test case, is an InvalidArgument. hegel.composite and hegel.generators.composite are the same function.

hegel.generators.builds(target: Callable[[...], T], /, *args: Any, **kwargs: Any) → Generator[T]

Generate values by calling target with arguments drawn from the given generators: builds(f, gs.integers(), name=gs.text()) draws f(n, name=s).

Required parameters of target that are not given, and that have a type annotation, are filled in from from_type() of the annotation; parameters with defaults are left to their defaults. The value is printed as the call, f(0, name=''). A target that is not callable, or an argument that is not a generator, is an InvalidArgument.

@dataclass
class Point:
    x: int
    y: int

point = tc.draw(gs.builds(Point))
origin_row = tc.draw(gs.builds(Point, y=gs.just(0)))
hegel.generators.recursive(leaf: Generator[T], branch: Callable[[Generator[T]], Generator[T]], *, max_depth: int = DEFAULT_MAX_DEPTH, max_leaves: int = DEFAULT_MAX_LEAVES) → Generator[T]

Generate recursively structured data: trees whose leaves come from leaf.

branch receives a generator of sub-values (each a leaf or a further branch) and returns a generator combining some of them into a compound value. Values are bounded by max_depth (nesting, default 32) and max_leaves (default 100; an attempt drawing more leaves is discarded and retried). Values shrink toward a single leaf.

json = gs.recursive(
    gs.none() | gs.booleans() | gs.floats() | gs.text(),
    lambda children: gs.lists(children) | gs.dicts(gs.text(), children),
)

A negative max_depth, or max_leaves below 1, is an InvalidArgument. For mutually recursive definitions, use deferred().

hegel.generators.deferred(definition: Callable[[], Generator[T]]) → Generator[T]

A generator whose definition is evaluated on first use, enabling recursive and mutually recursive definitions.

definition is a function of no arguments returning a generator. It is called once, the first time the generator is drawn from (or its label is needed), so it can refer to generators defined after it, including the deferred generator itself:

tree = gs.deferred(lambda: gs.none() | gs.tuples(tree, tree))

Draws nested so deeply that Python’s recursion limit is in sight abandon the test case as too large, so a definition that always refers back to itself cannot recurse forever: a test drawing from one fails with FailedHealthCheck. A definition that resolves only to itself is an InvalidArgument.

Inferring generators from types

hegel.generators.from_type(type_: Any) → Generator[Any]

A generator of instances of type_, inferred from the type.

type_ may be:

  • a type registered with register_type_generator();

  • a builtin or standard-library value type (int, str, bytes, float, datetime.date, uuid.UUID, decimal.Decimal, ipaddress types, …);

  • a parameterised collection or typing construct (list[int], dict[str, float], tuple[int, ...], int | None, Literal[...], Optional, Annotated, NewType, a TypeVar by its bound or constraints, and type aliases);

  • an Enum, sampled with sampled_from();

  • a dataclass or TypedDict, built from its field annotations;

  • an abstract class or protocol, by its resolvable subclasses;

  • any other class whose constructor’s required parameters are all annotated, built with builds() (annotated optional parameters are either left to their defaults or generated).

A type that cannot be resolved (a required constructor parameter without an annotation, an abstract class or protocol with no resolvable subclass, an unresolved string annotation) is a ResolutionFailed, raised when the generator is built.

pairs = tc.draw(gs.from_type(list[tuple[int, str]]))
hegel.generators.register_type_generator(type_: Any, generator: Generator[Any] | Callable[[Any], Generator[Any]]) → None

Make from_type() of type_ (and so builds() inference of a parameter annotated with it) use generator.

generator is a generator, or a callable that takes the type asked for (a parameterisation such as MyBox[int], for a generic) and returns one. from_type of a class with no registration of its own but with registered subclasses draws from those subclasses’ generators. Registering again replaces the earlier registration. A string in place of a type is an InvalidArgument.

gs.register_type_generator(Money, gs.integers(0, 10**6).map(Money))

Dates and times

The date and time generators live in the temporal namespace, with the names every Hegel frontend uses for them:

when = tc.draw(gs.temporal.datetimes(zones=gs.temporal.zones()))
hegel.generators.temporal.dates(min_value: date | None = None, max_value: date | None = None, *, weekdays: Iterable[int] | None = None, months: Iterable[int] | None = None) → Generator[date]

Generate datetime.date objects in [min_value, max_value], inclusive, shrinking toward 2000-01-01 (or the bound nearest it).

Either bound may be omitted: a missing bound is the end of the range datetime supports. One draw in twenty on average targets a date tests tend to get wrong: the leap days nearest the bounds, the year boundaries, the 2038 and 2106 overflow days and the days of an ISO week 53.

weekdays restricts the draw to those days of the week, numbered as datetime.date.weekday() does (Monday is 0, Sunday 6, so weekdays=[5, 6] draws weekends), and months to those months, numbered 1 to 12. A drawn date outside them is moved to the nearest allowed date inside the bounds rather than rejected, so the draw never filters, and the dates still shrink toward 2000-01-01.

Bounds that are not dates (a datetime is not accepted), min_value > max_value, an empty or out-of-range weekdays or months, or bounds holding no allowed date are an InvalidArgument.

hegel.generators.temporal.times(min_value: time | None = None, max_value: time | None = None, *, zones: Generator[Any] | None = None, precision: str = 'microseconds') → Generator[time]

Generate datetime.time objects in [min_value, max_value], inclusive, shrinking toward midnight.

Either bound may be omitted, and a bound given must be naive. The times are naive too, unless zones is given: a generator of datetime.tzinfo objects (or None), one of which is attached to each time. fold is never set. A time has no date, so a zone whose offset depends on the date, as a zoneinfo.ZoneInfo from zones() does, gives it no utcoffset(); offsets() generates zones that do.

precision names the unit every drawn time is a whole number of, as the timespec argument of isoformat() does: "microseconds" (the default), "milliseconds", "seconds", "minutes" or "hours".

Bounds that are not naive times, min_value > max_value, bounds holding no time at the precision, or a zones generator producing something other than tzinfo objects or None are an InvalidArgument.

hegel.generators.temporal.datetimes(min_value: datetime | None = None, max_value: datetime | None = None, *, zones: Generator[Any] | None = None, source: ZoneSource | None = None, allow_imaginary: bool = True, ambiguous: str = 'both', precision: str = 'microseconds') → Generator[datetime]

Generate datetime.datetime objects, naive or aware, in [min_value, max_value], shrinking toward 2000-01-01 00:00 (or the bound nearest it).

Naive bounds. With naive bounds, or none (a missing bound is datetime.min or datetime.max), the bounds limit the wall-clock time. The datetimes are naive unless zones is given: a generator of datetime.tzinfo objects (or None), such as zones(), one of which is attached to each drawn wall-clock time:

aware = tc.draw(gs.temporal.datetimes(zones=gs.temporal.zones()))

Aware bounds. With aware bounds the bounds are moments in time, compared as such however their time zones differ, and every datetime is aware and lies between them in a zone drawn from zones, which defaults to zones() and must not generate None:

this_year = gs.temporal.datetimes(
    dt.datetime(2026, 1, 1, tzinfo=dt.UTC), dt.datetime(2027, 1, 1, tzinfo=dt.UTC)
)

One bound may be omitted; passing one naive and one aware bound is an error.

Zones and their data. The engine draws the wall time in a zone against a ZoneSource’s data for it, and which source that is depends on zones:

  • With no zones (and aware bounds), the zones are zones(source=source).

  • With a zones() generator, its own source is used; set it with zones(source=...). Passing source here as well is an error.

  • With any other generator (zones().filter(...), gs.sampled_from([...]), gs.just(...)), a zoneinfo.ZoneInfo it generates is looked up by its key in source, by default default_zone_source() as it was when this generator was built. A key that source does not know is an InvalidArgument naming the zone, so pass the source that has it.

source without zones or aware bounds, when the datetimes are naive, is an error.

Transitions. In a zone drawn against a source, one draw in twenty on average lands within a second, an hour or a day of one of the zone’s daylight-saving or offset transitions, or of a well-known instant such as the Unix epoch or the end of the signed 32-bit epoch, so the skipped and repeated wall times where date bugs live are generated deliberately. A repeated wall time is drawn with either value of fold by default; ambiguous chooses "earlier" (fold=0) or "later" (fold=1) instead of "both". A skipped wall time (one the clocks jumped over, which datetime represents but which never occurred) is drawn by default, because malformed timestamps are a common source of bugs; with allow_imaginary=False the engine draws a real wall time instead. With aware bounds, a zone that has no wall time between them at the precision rejects the test case.

Other tzinfo objects. A fixed offset (datetime.timezone) or any other tzinfo that is not a zoneinfo.ZoneInfo with a key has no data in a zone source, so nothing aims at its transitions and Hegel goes by what the tzinfo itself reports. With naive bounds the drawn wall time is attached to it: a repeated one gets the fold that ambiguous asks for, and a skipped one rejects the test case under allow_imaginary=False. With aware bounds a moment between them is drawn and converted to the zone, so it is never a skipped wall time, and a repeated one is given the reading ambiguous asks for; the test case is rejected when that reading, or the nearest wall time at the precision, lies outside the bounds. A tzinfo that ignores fold, as pytz’s do, never reports a repeated wall time.

Precision. precision names the unit every drawn time of day is a whole number of, as the timespec argument of isoformat() does: "microseconds" (the default), "milliseconds", "seconds", "minutes" or "hours".

Bounds that are not datetimes, a mix of a naive and an aware bound, min_value > max_value, bounds holding no wall time at the precision, a misplaced source, or a zones generator producing something other than tzinfo objects (or None with aware bounds) are an InvalidArgument.

hegel.generators.temporal.zoned_datetimes(min_value: datetime | None = None, max_value: datetime | None = None, *, zones: Generator[Any] | None = None, source: ZoneSource | None = None, allow_imaginary: bool = True, ambiguous: str = 'both', precision: str = 'microseconds') → Generator[datetime]

Generate aware datetime.datetime objects in [min_value, max_value], each in a zone drawn from zones, shrinking toward 2000-01-01 00:00 (or the bound nearest it) in UTC.

This is datetimes() for a test that wants only aware datetimes, and takes the same arguments: zones defaults to zones(source=source) and must not generate None, naive bounds (or none) limit the wall-clock time in the drawn zone, and aware bounds are moments in time. The engine draws the zone and the wall time together, so one draw in twenty on average lands near one of the zone’s transitions:

meeting = tc.draw(gs.temporal.zoned_datetimes(dt.datetime(2026, 1, 1)))

source is the ZoneSource whose data the zones are drawn against, as for datetimes(): that of the default zones, or the one a zoneinfo.ZoneInfo from a generator other than zones() is looked up in. Invalid arguments are those of datetimes().

hegel.generators.temporal.instants(min_value: datetime | None = None, max_value: datetime | None = None, *, precision: str = 'microseconds') → Generator[datetime]

Generate moments in time, as datetime.datetime objects in UTC (tzinfo is datetime.UTC), in [min_value, max_value], shrinking toward 2000-01-01 00:00 UTC (or the bound nearest it).

Either bound may be omitted. A bound given must be aware, and bounds are compared as moments in time however their time zones differ; a missing bound is the end of the range a UTC datetime represents, and a bound beyond that range is clamped to it. One draw in twenty on average targets an instant tests tend to get wrong: the Unix epoch and its neighbours, the 32-bit and 64-bit second boundaries, leap days, or a transition of any time zone in Hegel’s database.

precision names the unit every drawn instant is a whole number of since the Unix epoch: "microseconds" (the default), "milliseconds", "seconds", "minutes" or "hours".

Bounds that are not aware datetimes, min_value > max_value, or bounds holding no instant at the precision in the UTC range are an InvalidArgument.

hegel.generators.temporal.durations(min_value: timedelta | None = None, max_value: timedelta | None = None, *, precision: str = 'microseconds') → Generator[timedelta]

Generate datetime.timedelta objects in [min_value, max_value], inclusive, shrinking toward zero. Either bound may be omitted: a missing bound is the end of the range datetime supports. One draw in twenty on average targets a round duration, such as a second, an hour, a day, 25 hours or a week, of either sign.

precision names the unit every drawn delta is a whole number of: "microseconds" (the default), "milliseconds", "seconds", "minutes" or "hours".

Bounds that are not timedelta objects, min_value > max_value, or bounds holding no delta at the precision are an InvalidArgument.

hegel.generators.temporal.spans(*, years: tuple[int, int] | None = None, months: tuple[int, int] | None = None, weeks: tuple[int, int] | None = None, days: tuple[int, int] | None = None, hours: tuple[int, int] | None = None, minutes: tuple[int, int] | None = None, seconds: tuple[int, int] | None = None, milliseconds: tuple[int, int] | None = None, microseconds: tuple[int, int] | None = None, nanoseconds: tuple[int, int] | None = None, sign: str = 'uniform') → Generator[Span]

Generate calendar spans, as Span objects, shrinking toward the zero span (or the span nearest it in each unit’s bounds).

Each unit’s argument is an inclusive (min, max) bound on its signed value. Naming any unit draws only the named units, leaving the others 0, so spans(months=(0, 11), days=(0, 30)) draws months and days; naming none draws every unit, each within the 64-bit signed range.

sign says how the units’ signs are drawn: "uniform" (the default) draws one sign for the whole span, as the JavaScript Temporal Duration requires; "mixed" signs each unit on its own, as java.time.Period allows; "non_negative" draws only magnitudes. Under "uniform" a negative span draws each unit’s magnitude within [max(-max, 0), -min].

A bound that is not a (min, max) tuple of ints with min <= max within the 64-bit signed range, an unknown sign, a negative min under "non_negative", or bounds that leave "uniform" no sign every unit can take are an InvalidArgument.

class hegel.generators.temporal.Span(years: int = 0, months: int = 0, weeks: int = 0, days: int = 0, hours: int = 0, minutes: int = 0, seconds: int = 0, milliseconds: int = 0, microseconds: int = 0, nanoseconds: int = 0)

A calendar span: a count of each unit from years to nanoseconds, such as “1 month and 2 days”, which datetime.timedelta cannot represent because a month or a day has no fixed length. Each count is an int in the 64-bit signed range.

str(span) is the form every Hegel frontend prints a span in: the nonzero units, largest first, with their suffixes, and "0s" for the zero span. A span with no negative unit has no signs ("1y 2mo"), one with no positive unit has one leading - ("-3d 4h" is minus three days and minus four hours), and one with both signs each unit ("-3d +4h"). The repr names the nonzero units as keyword arguments.

hegel.generators.temporal.zones(*, names: Iterable[str] | None = None, no_cache: bool = False, allow_links: bool = True, allow_legacy: bool = False, source: ZoneSource | None = None) → Generator[ZoneInfo]

Generate IANA time zones, as zoneinfo.ZoneInfo objects, shrinking toward UTC.

The zones are those zone_names() names, with the same names, allow_links, allow_legacy and source arguments; a name in names must also be one this Python can load. With no_cache=True each zone is built with zoneinfo.ZoneInfo.no_cache(), so it is not the same object as ZoneInfo(key).

datetimes() and zoned_datetimes() draw their wall times against the source’s data for the zone, so a source other than ZoneSource.zoneinfo() aims at gaps and folds that the ZoneInfo attached to the value may not have. A name the source draws that zoneinfo cannot load is an InvalidArgument.

hegel.generators.temporal.zone_names(*, names: Iterable[str] | None = None, allow_links: bool = True, allow_legacy: bool = False, source: ZoneSource | None = None) → Generator[str]

Generate IANA time zone names, such as "America/New_York", shrinking toward "UTC".

The names are those the zone source knows, by default default_zone_source(), which is ZoneSource.zoneinfo() unless changed: the names zoneinfo.available_timezones() lists, so every name generated can be loaded with zoneinfo.ZoneInfo. On a system without a time zone database (Windows, say) install the tzdata package, or pass source=ZoneSource.bundled() for the names of the engine’s own database. The posix/ and right/ variants some systems carry are never generated. By default link names such as "Asia/Calcutta" are included and legacy names such as "EST5EDT" and "US/Eastern" are excluded; allow_links and allow_legacy switch each.

names restricts the draw to those names, each of which the source must know. allow_links and allow_legacy do not apply to an explicit list, and passing either with one is an error.

The generator reads the default source, and the names its source knows, when it is built: a source changed afterwards does not change what it draws.

Half the draws are uniform over the names and half weighted toward zones with a rare feature (a fractional offset, negative daylight saving, a skipped day, …), so each is reached by a short run. A name shrinks to a zone a reader recognises: real zones with a whole-hour offset and a simple daylight-saving rule first, then the other real zones, then the Etc/GMT family, then the legacy names. Which names are links or legacy, their features and their order come from Hegel’s bundled database, so they are the same on every machine; a name it lacks comes last, with the features of the source’s data for it.

A names list that is empty or holds a name the source does not know, or a source with no name the flags allow, is an InvalidArgument.

hegel.generators.temporal.offsets(min_value: timedelta | None = None, max_value: timedelta | None = None, *, granularity: str = 'seconds') → Generator[timezone]

Generate fixed UTC offsets, as datetime.timezone objects, with an offset in [min_value, max_value], shrinking toward datetime.timezone.utc.

Either bound may be omitted. The bounds are whole seconds within the day datetime.timezone allows, from -23:59:59 to +23:59:59, which a missing bound is the end of. granularity names the unit every drawn offset is a whole number of: "hours", "quarter_hours", "minutes" or "seconds" (the default). One draw in twenty on average targets an offset some IANA zone has used, or a limit such as ±18:00 or ±00:00:01, when it lies in the bounds at the granularity.

Bounds that are not whole-second timedelta objects within the range, min_value > max_value, or bounds holding no offset at the granularity are an InvalidArgument.

hegel.generators.temporal.tzdb_version() → str

The IANA release of the time zone database bundled in Hegel’s engine, such as "2026e".

The bundled database is what ZoneSource.bundled() draws against, and it always supplies the zone names’ tags and shrink order. Zoned draws use the default zone source, zoneinfo’s database, whose release ZoneSource.version reports.

Time zone data

Zoned draws aim at the gaps and folds of the zone’s transitions, so they need the same time zone data as the code under test. They draw against a ZoneSource: by default ZoneSource.zoneinfo(), the database zoneinfo itself reads (the system’s zone files, or the tzdata package), so a zone has exactly the transitions its ZoneInfo has. Where zoneinfo finds no database at all (Windows without the tzdata package), a generator that needs the default source’s zones raises InvalidArgument when it is built, saying to install tzdata.

zones(), zone_names(), datetimes() and zoned_datetimes() take a source to draw against another one, and set_default_zone_source() changes the default. A generator reads its source, and the names the source knows, when it is built, so build a source once, outside the test body, and set the default before building generators:

BUNDLED = gs.temporal.ZoneSource.bundled()
zoned = gs.temporal.zoned_datetimes(source=BUNDLED)
zones = gs.temporal.zones(source=BUNDLED)

An integration with another date and time library fills a ZoneSource() with that library’s data: TZif files, ZoneData given as fields, or a ZoneOracle it answers lookups for, added up front or loaded the first time a draw needs a zone. ZoneSource.info(), ZoneSource.resolve() and ZoneSource.offset_at() read back what the engine made of it.

class hegel.generators.temporal.ZoneSource

The time zone data zoned draws are generated against: which zones exist, and their transitions and rules, so that the gaps and folds the engine aims at are those of the database the code under test uses.

By default every draw uses zoneinfo(), zoneinfo’s own database; set_default_zone_source() changes that, and zones(), zone_names(), datetimes() and zoned_datetimes() take a source for one generator. bundled() is the engine’s own database.

ZoneSource() is an empty source, for an integration with another date and time library to fill: with add_tzif(), add_zone(), add_oracle() and add_link(), or lazily, by declaring the names it knows with declare() and supplying each zone’s data when a draw first needs it through set_loader(). Whatever its shape, the engine checks the data, and an error in it raises InvalidArgument. info(), resolve() and offset_at() report what the source holds, and name in source whether it knows a name.

Build a source once, at module level or in a fixture, rather than in a test body, and fill it before building generators from it: a source may be filled while it is in use, but a generator reads the names its source knows when the generator is built, so a name added afterwards is drawn only by generators built after that.

static bundled() → ZoneSource

The IANA database bundled in Hegel’s engine, of release tzdb_version(), the same on every machine. It cannot be changed.

static zoneinfo() → ZoneSource

The database zoneinfo reads, the default source.

Its names are those zoneinfo.available_timezones() lists, and each zone’s data is read from the TZif file zoneinfo.ZoneInfo would load for it (from the directories of zoneinfo.TZPATH, then from the tzdata package) the first time a draw needs it, so a zone a test draws has exactly the transitions zoneinfo gives it. The names and the version are read when the source is first used, and the files when each zone is, so a source made before zoneinfo.reset_tzpath() changes the search path reads its zones from the new one.

Where zoneinfo finds no database (Windows without the tzdata package, say) the source has no names, and building a generator that draws its zones is an InvalidArgument.

property version: str

The release of the source’s database: tzdb_version() for bundled(); for zoneinfo(), the release the zone files’ directory records in its tzdata.zi or +VERSION, or tzdata.IANA_VERSION when the files come from the tzdata package; otherwise what was set, or "". Failure output does not report it.

add_tzif(name: str, data: bytes) → None

Add the zone name from the contents of a TZif file (version 2 or later), such as one under /usr/share/zoneinfo.

add_zone(name: str, data: ZoneData) → None

Add the zone name from its data given as fields.

add_oracle(name: str, oracle: ZoneOracle) → None

Add the zone name by probing oracle now.

Make name another name for the zone target, which need not have been added yet.

declare(names: Iterable[str]) → None

Declare names the source knows whose data comes later, from the loader or from an add_* call made before a draw needs it.

set_loader(loader: Callable[[str], bytes | ZoneData | ZoneOracle | str | None] | None) → None

Supply a zone’s data the first time a draw or query needs it: loader(name) returns the zone’s TZif bytes, a ZoneData, a ZoneOracle, the name of the zone it is a link to, or None for a name it does not know.

The loader is asked for declared names and for any other name a generator or query names. What it returns for a name is kept, so it is normally asked once per name, but it may be asked for the same name again: from two threads that need it at once, and after a call that raised. It may be called from any thread that draws, several at once, and must not draw itself. An exception it raises fails the draw or query with InvalidArgument, whose __cause__ is that exception.

A new loader replaces the previous one, and None removes it. The source holds the loader until then, or until nothing uses the source any more.

info(name: str) → ZoneNameInfo | None

What the source knows about the name name, or None for a name it does not know. A name the source has declared but not yet loaded is loaded through the loader when describing it needs its data.

__contains__(name: object) → bool

Whether the source knows the time zone name name.

resolve(name: str, wall_time: datetime) → ZoneResolution

Read the naive datetime wall_time as a wall-clock time in the zone name: whether the zone’s clocks showed it once, never or twice, the offsets around it, and the moment it denotes given its fold. An integration checks the data it loaded with this, by comparing a sample of wall times with its library’s answers.

A name the source does not know, an aware wall_time, or a moment outside the range datetime represents is an InvalidArgument.

offset_at(name: str, instant: datetime) → ZoneType

The ZoneType (UTC offset, daylight-saving flag and abbreviation) the zone name has in force at the aware datetime instant. A name the source does not know or a naive instant is an InvalidArgument.

hegel.generators.temporal.default_zone_source() → ZoneSource

The zone source a generator uses when not given one: ZoneSource.zoneinfo() unless set_default_zone_source() set another. A generator reads it once, when it is built.

hegel.generators.temporal.set_default_zone_source(source: ZoneSource) → ZoneSource

Make source the zone source of every generator built from now on without one of its own, and return the source it replaces, to restore afterwards.

A generator reads the default when it is built and keeps what it read, so set it before building generators: at the top of conftest.py, say, before test modules that build generators at import time are loaded. It is one setting for the whole process, all threads included.

class hegel.generators.temporal.ZoneNameInfo(primary_name: str, is_link: bool, is_legacy: bool, rank: int)

What a ZoneSource knows about a time zone name, from ZoneSource.info(): primary_name, the zone whose data applies (the link target for a link, the name itself otherwise); is_link and is_legacy, which the allow_links and allow_legacy arguments of zone_names() go by; and rank, the name’s place in the order names shrink in, 0 for "UTC".

class hegel.generators.temporal.ZoneResolution(kind: str, offset_before: timedelta, offset_after: timedelta, instant: datetime)

How a ZoneSource’s data reads a wall-clock time in a zone, from ZoneSource.resolve().

kind is "unique" for a wall time the zone’s clocks showed once, "gap" for one they skipped and "fold" for one they showed twice. For a gap or a fold offset_before and offset_after are the UTC offsets in force before and after the transition; otherwise both are the offset in force. instant is the moment the wall time denotes, in UTC, read as datetime reads it: with offset_before when its fold is 0 and offset_after when it is 1.

class hegel.generators.temporal.ZoneType(offset: timedelta, is_dst: bool = False, abbreviation: str = '')

A local time type of a zone: its UTC offset, whether it is daylight saving time, and its abbreviation, such as ZoneType(dt.timedelta(hours=1), True, "BST"). The offset is a whole number of seconds less than two days from zero.

class hegel.generators.temporal.ZoneData(initial: ZoneType, transitions: Sequence[tuple[int, ZoneType]] = (), rule: ZoneRule | None = None, infer_after: int | None = None)

A zone’s data, given as fields, as a TZif file holds it.

initial is in force before the first of transitions, a sequence of (instant, type) pairs strictly ascending by instant, in seconds since the Unix epoch, each putting the ZoneType type in force from then on. After the last transition the zone follows rule, or, with infer_after set to the last year the transitions cover, a yearly rule the engine infers from that year’s transitions and the year before’s; with neither, the last type holds for ever.

class hegel.generators.temporal.ZoneRule(standard: ZoneType, dst: ZoneType | None = None, dst_start: RuleDate | None = None, dst_end: RuleDate | None = None)

A zone’s rule after its last explicit transition: standard always, or standard with dst in force each year from dst_start to dst_end.

class hegel.generators.temporal.RuleDate(kind: str, day: int = 0, month: int = 0, week: int = 0, weekday: int = 0, time: timedelta = datetime.timedelta(seconds=7200))

When a yearly daylight-saving rule changes the clocks: time after local midnight (in the offset in force before the change) of a day of the year, as the Jn, n and Mm.w.d forms of a POSIX TZ string name it. time is a whole number of seconds from -167 to 167 hours, the range a TZif file allows. Build one with julian(), zero_based() or month_week_day().

classmethod julian(day: int, time: timedelta = dt.timedelta(hours=2)) → RuleDate

Day day of the year, from 1 to 365, never counting February 29 (Jn).

classmethod zero_based(day: int, time: timedelta = dt.timedelta(hours=2)) → RuleDate

Day day of the year counted from 0, from 0 to 365, counting February 29 in leap years (n).

classmethod month_week_day(month: int, week: int, weekday: int, time: timedelta = dt.timedelta(hours=2)) → RuleDate

The week-th weekday of month (Mm.w.d): week from 1 to 5, 5 meaning the last, and weekday numbered as datetime.date.weekday() numbers it, Monday 0 to Sunday 6.

class hegel.generators.temporal.ZoneOracle(offset_at: Callable[[int], ZoneType], *, first_year: int, last_year: int, after: str, next_transition: Callable[[int], int | None] | None = None)

A zone given by a library that answers lookups but does not expose its data. offset_at(instant) returns the ZoneType in force at instant (seconds since the Unix epoch), and the optional next_transition(instant) the first instant after it at which the type changes, or None when it never changes again.

The engine probes the oracle over the years first_year to last_year, asking next_transition for each transition in turn or, without it, sampling offset_at once a day and bisecting each change to the second. Before first_year the type at its start holds; after last_year, after="hold" holds the last type and after="infer" infers a yearly rule from the last two years.

The top-level names the date and time generators had before they moved, gs.dates, gs.times, gs.datetimes (with its timezones= argument), gs.timedeltas and gs.timezones, still work, with the arguments they were released with, but emit a DeprecationWarning; use the gs.temporal names instead.

Identifiers and network values

hegel.generators.uuids(*, version: int | None = None, allow_nil: bool = False) → Generator[UUID]

Generate uuid.UUID objects.

With version (1 to 5) every UUID is an RFC 4122 UUID of that version. Without it, the UUIDs are arbitrary 128-bit values, most of which have no RFC 4122 version. The nil UUID (all zeros) is generated only with allow_nil=True, which cannot be combined with version. Invalid arguments are an InvalidArgument.

hegel.generators.ip_addresses(*, v: int | None = None, network: Any = None) → Generator[Any]

Generate IP addresses, as ipaddress.IPv4Address or ipaddress.IPv6Address objects.

v=4 or v=6 picks one version; by default either may be generated. network (a string such as "10.0.0.0/8", or an ipaddress.IPv4Network or ipaddress.IPv6Network) restricts the addresses to that network, including its network and broadcast addresses. Addresses shrink toward the lowest one: 0.0.0.0, ::, or the network address. A v other than 4 or 6, or one that disagrees with network, is an InvalidArgument.

hegel.generators.emails() → Generator[str]

Generate email addresses, as strings.

Each is a local part of RFC 5322 atext characters and dots, @, and a domain as domains() generates. The addresses are well formed, not real.

hegel.generators.domains(*, max_length: int = 255) → Generator[str]

Generate fully qualified domain names of at most max_length characters, as strings, ending in a top-level domain from the IANA list. max_length must be between 4 and 255 (the default), or it is an InvalidArgument.

hegel.generators.urls() → Generator[str]

Generate RFC 3986 URLs, as strings, with an http or https scheme and a host as domains() generates.

The generator class

Every generator is an instance of Generator, which provides the methods for transforming one generator into another. Subclassing it directly is rarely necessary: composite() covers almost every case. A subclass that should be drawn with TestCase.draw implements do_draw_and_print, which prints the value as it draws it; see Printing values.

class hegel.generators.Generator

A recipe for drawing values of some type from a TestCase.

Generators are built by the functions in hegel.generators and drawn from with TestCase.draw. They are immutable descriptions of how to make a value: the same generator can be drawn from any number of times, in any number of tests. Every generator has the combinators map(), filter() and flat_map(), and a | b is one_of() of the two:

evens = gs.integers().map(lambda n: n * 2)
small = gs.integers().filter(lambda n: abs(n) < 100)
numbers = gs.integers() | gs.floats()

Most custom generators are best written with composite(). Subclassing is for generators that need to control how their values are printed or how they are labelled.

Printing is the generator’s job. TestCase.draw reports the drawn value, so it needs a printable generator: one that implements do_draw_and_print(), drawing its components with tc.draw_and_print(component, printer) and writing its own syntax to the printer as it goes. Such a subclass gets do_draw() for free:

class Coords(gs.Generator[tuple[int, int]]):
    def do_draw_and_print(self, tc, printer):
        with printer.group("Coord(", ")"):
            x = tc.draw_and_print(gs.integers(0, 9), printer)
            printer.separator()
            y = tc.draw_and_print(gs.integers(0, 9), printer)
        return (x, y)

A subclass that implements only do_draw() draws silently: it can be drawn with TestCase.draw_silent or used as the source of map(), and print_as_repr() or print_with() make it printable. Drawing it with tc.draw raises NotPrintable. label identifies the generator to the engine’s shrinker: generators drawing the same shape of value share one. A subclass that sets no label of its own is labelled by its qualified class name, so two generator classes shrink apart.

do_draw(tc: TestCase) → T

Produce a value without printing it. Draw component generators with tc.draw_silent (or tc.draw_and_print), never by calling their do_draw directly, so each gets a span of its own.

The default runs do_draw_and_print() with a no-op printer, so a printable generator writes its drawing logic once.

do_draw_and_print(tc: TestCase, printer: PrettyPrinter) → T

Produce a value, printing its representation to printer as it is drawn. Must draw exactly the same choices as do_draw().

There is no default: a generator that does not implement it cannot print what it draws, and drawing it with tc.draw raises NotPrintable.

map(f: Callable[[T], U]) → Generator[U]

A generator of f(value) for each value this one generates.

The mapped value is what the failure report prints. f runs every time a value is drawn, and shrinking happens on the underlying value, so a mapped generator shrinks toward f of the source’s simplest value:

evens = gs.integers().map(lambda n: n * 2)
flat_map(f: Callable[[T], Generator[U]]) → Generator[U]

Generate a value, then draw from the generator f builds from it.

f must return a Generator; anything else is an InvalidArgument. Only the final value is printed. Use this when the shape of one value depends on another:

lists_and_index = gs.integers(1, 10).flat_map(
    lambda n: gs.tuples(
        gs.lists(gs.integers(), min_size=n, max_size=n),
        gs.integers(0, n - 1),
    )
)

A composite() generator expresses the same dependency more readably, and is usually the better choice.

filter(predicate: Callable[[T], bool]) → Generator[T]

Keep only values satisfying predicate.

Each draw tries the source as many times as the engine’s HEGEL_FILTER_ATTEMPTS, which every Hegel library’s filter shares; if no attempt satisfies predicate, the test case is rejected as if by TestCase.assume. A filter that rejects most values therefore rejects many test cases, and may fail the filter_too_much health check: prefer generating the values you want directly (gs.integers(min_value=0) rather than gs.integers().filter(lambda n: n >= 0)). Chained filters combine into one, and filtering sampled_from() narrows its elements instead of retrying, so even a rare element is found.

print_with(print: Callable[[T, PrettyPrinter], None]) → Generator[T]

A generator of the same values that prints each one with print, in place of however this generator prints.

print is called as print(value, printer) with a PrettyPrinter to write the value’s representation into the failure report; it is only called when the output will be shown. It works on any generator, printable or not, and is the way to print a custom representation or mask a secret:

tokens = gs.text().print_with(lambda value, printer: printer.text("<token>"))
print_as_repr() → Generator[T]

A generator of the same values that prints each one as its repr (through PrettyPrinter.repr), in place of however this generator prints. This makes a subclass that implements only do_draw() printable.

print_as_call(function: str) → Generator[T]

For a mapped generator: print function(input) around the source generator’s own output instead of the mapped value.

This makes a value whose repr is unhelpful print as the call that built it:

points = gs.tuples(gs.integers(), gs.integers()).map(
    lambda t: Point(*t)
).print_as_call("Point")

prints a drawn point as Point((0, 0)). Calling it on a generator that is not the result of map(), or with an empty name, is an InvalidArgument.