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**127values 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
floatwith an integral value is accepted) ormin_value > max_valueis anInvalidArgument.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_exclusiveandmax_value_exclusiveset a bound that is itself excluded, in place of the inclusivemin_valueandmax_value; giving both forms of one bound is anInvalidArgument. Values shrink toward0.0, and toward simple values with few significant digits: integers before fractions.allow_nan,allow_infinityandallow_subnormaldefault 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 anInvalidArgument. Setting both bounds disables infinity; with one bound, the infinity on the unbounded side is allowed unlessallow_infinity=False. Subnormals are allowed when the range contains any.widthis 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=Falsewithmin_value=math.inf, ormin_value_exclusive=1.0withmax_value=1.0, say) are each anInvalidArgument.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))
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_sizeandmax_sizecharacters, shrinking toward shorter strings of simpler characters ("", then"0").Without
max_sizethe engine applies its default maximum for text: 100 characters, ormin_size + 100whenmin_sizeis larger than that, whatever the alphabet. A negative size ormax_size < min_sizeis anInvalidArgument.alphabetrestricts the characters: a string or sequence of characters, or acharacters()generator. Any other generator is anInvalidArgument; 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 acharacters()alphabet, with the same meanings, and cannot be combined withalphabet. Surrogate code points are never generated unless asked for by category.Unicode categories follow the Unicode version of the running Python’s
unicodedata, sostr.isalphaand 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, within0to0x10FFFF.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 unlesscategoriesnames them.include_characters: characters to allow whatever the other filters say.exclude_characters: characters never to generate.
categoriesandexclude_categoriescannot both be given. An unknown codec or category, an out-of-range code point, ormax_codepoint < min_codepointis anInvalidArgument. Categories follow the Unicode version of the running Python’sunicodedata.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 compiledre.Pattern(whose flags are honoured).By default the whole string matches, as
re.fullmatch()checks; withfullmatch=Falsethe string merely contains a match, asre.search()would find, and may have arbitrary text around it. (Hypothesis’sfrom_regexdefaults tofullmatch=False.)alphabetrestricts the characters the pattern’s character classes and.may produce, as a string of characters or acharacters()generator; it cannot be empty, and cannot be used with a bytes pattern. A bytes pattern generatesbytes, matching with the semantics ofrefor bytes (\wand 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 anInvalidArgumentwhen 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 itsstartrule (or the rule named bystart).The whole grammar language is supported: rules, terminals with string and regex patterns and priorities,
%import(including Lark’s bundledcommon,python,unicodeandlarkgrammars),%ignore,%declare,%override,%extendand 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 failedassume()does. The grammar is parsed and the strings generated by Hegel’s engine: Lark itself need not be installed.explicitmaps 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 anInvalidArgumentwhen drawn.alphabetrestricts the characters the terminals’ patterns may produce, as forfrom_regex(): a string of characters or acharacters()generator.max_sizecaps 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_depthcaps how deeply rules nest (default 200, at most 500).import_pathis the directory%imported grammars are read from:%import a.b.Xreadsa/b.larkfrom it, and Lark’s bundled grammars stand in when it has no such file. A relative import (%import .lib.X) ina/b.larkreadsa/lib.lark, and ingrammaritselflib.lark.A grammar Lark would reject, an undefined start rule, a cap below the smallest string the grammar can produce, or an
explicitgenerator for a terminal the grammar does not have is anInvalidArgumentwhen 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_sizeandmax_sizebytes, shrinking toward shorter strings of zero bytes.Without
max_sizethe engine applies its default maximum: 100 bytes, ormin_size + 100whenmin_sizeis larger than that. A negative size ormax_size < min_sizeis anInvalidArgument.
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 betweenmin_sizeandmax_sizeelements.max_sizedefaults to no fixed limit: the engine decides when to stop, and keeps lists reasonably short. Lists shrink toward fewer elements, and each element shrinks aselementsdoes.unique=Truerequires the elements to be distinct (and hashable).unique_byis a key function, or a tuple of them, each of whose results must be distinct across the list; it cannot be combined withunique. A duplicate element is discarded and another drawn in its place. When the elements are asampled_from()(under anymap()andfilter()), 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 amin_sizelarger than the number of distinct valueselementsis known to have, is anInvalidArgument.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 betweenmin_sizeandmax_sizemembers; the elements must be hashable. Sizes are as forlists(), 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, assets()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
keysand values fromvalues, with betweenmin_sizeandmax_sizeentries.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, usefixed_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 thatmappinggives 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 anInvalidArgument. 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 thatlists()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.elementsis a sequence (copied if mutable, so later changes to it do not affect the generator), any other iterable (read once), or anEnumclass, whose members are sampled in definition order. AFlagclass also yields the empty flag and combinations of its members. An empty collection, an enum with no members, or aset(which has no stable order to shrink in) is anInvalidArgument.colour = tc.draw(gs.sampled_from(["red", "green", "blue"]))
.filteron 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()orbuilds(), or as the result of aflat_map().
- hegel.generators.nothing() Generator[Any]¶
A generator with no values: every draw rejects the test case, as
TestCase.rejectdoes.one_of()drops it, soone_of(gs.nothing(), g)isg.
- 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 betweenmin_sizeandmax_sizeitems.With
replacement=True(the default) each item is chosen independently, so an element may appear more than once. Withreplacement=Falseeach element is used at most once, in the order drawn, so the size is capped atlen(elements). Amin_sizethat cannot be met is anInvalidArgumentwhen 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 forlists(), capped atlen(elements); amin_sizelarger than that is anInvalidArgumentwhen 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 | bisone_of(a, b). Nestedone_ofcalls 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 anInvalidArgument.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
Noneor a value frominner, shrinking towardNone. Passing something other than a generator is anInvalidArgument.
- hegel.generators.composite(function: Callable[[...], T]) Callable[[...], Generator[T]]¶
Define a generator as a function taking a
TestCasefirst.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.drawlike 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.compositeandhegel.generators.compositeare the same function.
- hegel.generators.builds(target: Callable[[...], T], /, *args: Any, **kwargs: Any) Generator[T]¶
Generate values by calling
targetwith arguments drawn from the given generators:builds(f, gs.integers(), name=gs.text())drawsf(n, name=s).Required parameters of
targetthat are not given, and that have a type annotation, are filled in fromfrom_type()of the annotation; parameters with defaults are left to their defaults. The value is printed as the call,f(0, name=''). Atargetthat is not callable, or an argument that is not a generator, is anInvalidArgument.@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.branchreceives 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 bymax_depth(nesting, default 32) andmax_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, ormax_leavesbelow 1, is anInvalidArgument. For mutually recursive definitions, usedeferred().
- hegel.generators.deferred(definition: Callable[[], Generator[T]]) Generator[T]¶
A generator whose definition is evaluated on first use, enabling recursive and mutually recursive definitions.
definitionis 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 anInvalidArgument.
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,ipaddresstypes, …);a parameterised collection or
typingconstruct (list[int],dict[str, float],tuple[int, ...],int | None,Literal[...],Optional,Annotated,NewType, aTypeVarby its bound or constraints, and type aliases);an
Enum, sampled withsampled_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()oftype_(and sobuilds()inference of a parameter annotated with it) usegenerator.generatoris a generator, or a callable that takes the type asked for (a parameterisation such asMyBox[int], for a generic) and returns one.from_typeof 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 anInvalidArgument.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.dateobjects 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
datetimesupports. 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.weekdaysrestricts the draw to those days of the week, numbered asdatetime.date.weekday()does (Monday is 0, Sunday 6, soweekdays=[5, 6]draws weekends), andmonthsto 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
datetimeis not accepted),min_value > max_value, an empty or out-of-rangeweekdaysormonths, or bounds holding no allowed date are anInvalidArgument.
- 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.timeobjects 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
zonesis given: a generator ofdatetime.tzinfoobjects (orNone), one of which is attached to each time.foldis never set. A time has no date, so a zone whose offset depends on the date, as azoneinfo.ZoneInfofromzones()does, gives it noutcoffset();offsets()generates zones that do.precisionnames the unit every drawn time is a whole number of, as thetimespecargument ofisoformat()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 azonesgenerator producing something other thantzinfoobjects orNoneare anInvalidArgument.
- 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.datetimeobjects, 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.minordatetime.max), the bounds limit the wall-clock time. The datetimes are naive unlesszonesis given: a generator ofdatetime.tzinfoobjects (orNone), such aszones(), 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 tozones()and must not generateNone: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 onzones:With no
zones(and aware bounds), the zones arezones(source=source).With a
zones()generator, its own source is used; set it withzones(source=...). Passingsourcehere as well is an error.With any other generator (
zones().filter(...),gs.sampled_from([...]),gs.just(...)), azoneinfo.ZoneInfoit generates is looked up by its key insource, by defaultdefault_zone_source()as it was when this generator was built. A key that source does not know is anInvalidArgumentnaming the zone, so pass the source that has it.
sourcewithoutzonesor 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
foldby default;ambiguouschooses"earlier"(fold=0) or"later"(fold=1) instead of"both". A skipped wall time (one the clocks jumped over, whichdatetimerepresents but which never occurred) is drawn by default, because malformed timestamps are a common source of bugs; withallow_imaginary=Falsethe 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 othertzinfothat is not azoneinfo.ZoneInfowith a key has no data in a zone source, so nothing aims at its transitions and Hegel goes by what thetzinfoitself reports. With naive bounds the drawn wall time is attached to it: a repeated one gets thefoldthatambiguousasks for, and a skipped one rejects the test case underallow_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 readingambiguousasks for; the test case is rejected when that reading, or the nearest wall time at the precision, lies outside the bounds. Atzinfothat ignoresfold, aspytz’s do, never reports a repeated wall time.Precision.
precisionnames the unit every drawn time of day is a whole number of, as thetimespecargument ofisoformat()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 misplacedsource, or azonesgenerator producing something other thantzinfoobjects (orNonewith aware bounds) are anInvalidArgument.
- 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.datetimeobjects in[min_value, max_value], each in a zone drawn fromzones, 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:zonesdefaults tozones(source=source)and must not generateNone, 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)))
sourceis theZoneSourcewhose data the zones are drawn against, as fordatetimes(): that of the defaultzones, or the one azoneinfo.ZoneInfofrom a generator other thanzones()is looked up in. Invalid arguments are those ofdatetimes().
- 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.datetimeobjects in UTC (tzinfoisdatetime.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
datetimerepresents, 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.precisionnames 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 anInvalidArgument.
- hegel.generators.temporal.durations(min_value: timedelta | None = None, max_value: timedelta | None = None, *, precision: str = 'microseconds') Generator[timedelta]¶
Generate
datetime.timedeltaobjects in[min_value, max_value], inclusive, shrinking toward zero. Either bound may be omitted: a missing bound is the end of the rangedatetimesupports. 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.precisionnames the unit every drawn delta is a whole number of:"microseconds"(the default),"milliseconds","seconds","minutes"or"hours".Bounds that are not
timedeltaobjects,min_value > max_value, or bounds holding no delta at the precision are anInvalidArgument.
- 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
Spanobjects, 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, sospans(months=(0, 11), days=(0, 30))draws months and days; naming none draws every unit, each within the 64-bit signed range.signsays how the units’ signs are drawn:"uniform"(the default) draws one sign for the whole span, as the JavaScript TemporalDurationrequires;"mixed"signs each unit on its own, asjava.time.Periodallows;"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 withmin <= maxwithin the 64-bit signed range, an unknownsign, a negativeminunder"non_negative", or bounds that leave"uniform"no sign every unit can take are anInvalidArgument.
- 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.timedeltacannot 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"). Thereprnames 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.ZoneInfoobjects, shrinking toward UTC.The zones are those
zone_names()names, with the samenames,allow_links,allow_legacyandsourcearguments; a name innamesmust also be one this Python can load. Withno_cache=Trueeach zone is built withzoneinfo.ZoneInfo.no_cache(), so it is not the same object asZoneInfo(key).datetimes()andzoned_datetimes()draw their wall times against the source’s data for the zone, so a source other thanZoneSource.zoneinfo()aims at gaps and folds that theZoneInfoattached to the value may not have. A name the source draws thatzoneinfocannot load is anInvalidArgument.
- 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
sourceknows, by defaultdefault_zone_source(), which isZoneSource.zoneinfo()unless changed: the nameszoneinfo.available_timezones()lists, so every name generated can be loaded withzoneinfo.ZoneInfo. On a system without a time zone database (Windows, say) install thetzdatapackage, or passsource=ZoneSource.bundled()for the names of the engine’s own database. Theposix/andright/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_linksandallow_legacyswitch each.namesrestricts the draw to those names, each of which the source must know.allow_linksandallow_legacydo 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/GMTfamily, 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
nameslist that is empty or holds a name the source does not know, or a source with no name the flags allow, is anInvalidArgument.
- 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.timezoneobjects, with an offset in[min_value, max_value], shrinking towarddatetime.timezone.utc.Either bound may be omitted. The bounds are whole seconds within the day
datetime.timezoneallows, from -23:59:59 to +23:59:59, which a missing bound is the end of.granularitynames 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
timedeltaobjects within the range,min_value > max_value, or bounds holding no offset at the granularity are anInvalidArgument.
- 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 releaseZoneSource.versionreports.
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, andzones(),zone_names(),datetimes()andzoned_datetimes()take asourcefor 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: withadd_tzif(),add_zone(),add_oracle()andadd_link(), or lazily, by declaring the names it knows withdeclare()and supplying each zone’s data when a draw first needs it throughset_loader(). Whatever its shape, the engine checks the data, and an error in it raisesInvalidArgument.info(),resolve()andoffset_at()report what the source holds, andname in sourcewhether 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
zoneinforeads, the default source.Its names are those
zoneinfo.available_timezones()lists, and each zone’s data is read from the TZif filezoneinfo.ZoneInfowould load for it (from the directories ofzoneinfo.TZPATH, then from thetzdatapackage) the first time a draw needs it, so a zone a test draws has exactly the transitionszoneinfogives it. The names and theversionare read when the source is first used, and the files when each zone is, so a source made beforezoneinfo.reset_tzpath()changes the search path reads its zones from the new one.Where
zoneinfofinds no database (Windows without thetzdatapackage, say) the source has no names, and building a generator that draws its zones is anInvalidArgument.
- property version: str¶
The release of the source’s database:
tzdb_version()forbundled(); forzoneinfo(), the release the zone files’ directory records in itstzdata.zior+VERSION, ortzdata.IANA_VERSIONwhen the files come from thetzdatapackage; otherwise what was set, or"". Failure output does not report it.
- add_tzif(name: str, data: bytes) None¶
Add the zone
namefrom the contents of a TZif file (version 2 or later), such as one under/usr/share/zoneinfo.
- add_oracle(name: str, oracle: ZoneOracle) None¶
Add the zone
nameby probingoraclenow.
- add_link(name: str, target: str) None¶
Make
nameanother name for the zonetarget, 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, aZoneData, aZoneOracle, the name of the zone it is a link to, orNonefor 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
Noneremoves 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, orNonefor 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.
- resolve(name: str, wall_time: datetime) ZoneResolution¶
Read the naive datetime
wall_timeas a wall-clock time in the zonename: whether the zone’s clocks showed it once, never or twice, the offsets around it, and the moment it denotes given itsfold. 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 rangedatetimerepresents is anInvalidArgument.
- hegel.generators.temporal.default_zone_source() ZoneSource¶
The zone source a generator uses when not given one:
ZoneSource.zoneinfo()unlessset_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
sourcethe 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
ZoneSourceknows about a time zone name, fromZoneSource.info():primary_name, the zone whose data applies (the link target for a link, the name itself otherwise);is_linkandis_legacy, which theallow_linksandallow_legacyarguments ofzone_names()go by; andrank, 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, fromZoneSource.resolve().kindis"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 foldoffset_beforeandoffset_afterare the UTC offsets in force before and after the transition; otherwise both are the offset in force.instantis the moment the wall time denotes, in UTC, read asdatetimereads it: withoffset_beforewhen itsfoldis 0 andoffset_afterwhen 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.
initialis in force before the first oftransitions, a sequence of(instant, type)pairs strictly ascending byinstant, in seconds since the Unix epoch, each putting theZoneTypetypein force from then on. After the last transition the zone followsrule, or, withinfer_afterset 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:
standardalways, orstandardwithdstin force each year fromdst_starttodst_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:
timeafter local midnight (in the offset in force before the change) of a day of the year, as theJn,nandMm.w.dforms of a POSIX TZ string name it.timeis a whole number of seconds from -167 to 167 hours, the range a TZif file allows. Build one withjulian(),zero_based()ormonth_week_day().- classmethod julian(day: int, time: timedelta = dt.timedelta(hours=2)) RuleDate¶
Day
dayof the year, from 1 to 365, never counting February 29 (Jn).
- 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 theZoneTypein force atinstant(seconds since the Unix epoch), and the optionalnext_transition(instant)the first instant after it at which the type changes, orNonewhen it never changes again.The engine probes the oracle over the years
first_yeartolast_year, askingnext_transitionfor each transition in turn or, without it, samplingoffset_atonce a day and bisecting each change to the second. Beforefirst_yearthe type at its start holds; afterlast_year,after="hold"holds the last type andafter="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.UUIDobjects.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 withallow_nil=True, which cannot be combined withversion. Invalid arguments are anInvalidArgument.
- hegel.generators.ip_addresses(*, v: int | None = None, network: Any = None) Generator[Any]¶
Generate IP addresses, as
ipaddress.IPv4Addressoripaddress.IPv6Addressobjects.v=4orv=6picks one version; by default either may be generated.network(a string such as"10.0.0.0/8", or anipaddress.IPv4Networkoripaddress.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. Avother than 4 or 6, or one that disagrees withnetwork, is anInvalidArgument.
- hegel.generators.emails() Generator[str]¶
Generate email addresses, as strings.
Each is a local part of RFC 5322
atextcharacters and dots,@, and a domain asdomains()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_lengthcharacters, as strings, ending in a top-level domain from the IANA list.max_lengthmust be between 4 and 255 (the default), or it is anInvalidArgument.
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.generatorsand drawn from withTestCase.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 combinatorsmap(),filter()andflat_map(), anda | bisone_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.drawreports the drawn value, so it needs a printable generator: one that implementsdo_draw_and_print(), drawing its components withtc.draw_and_print(component, printer)and writing its own syntax to the printer as it goes. Such a subclass getsdo_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 withTestCase.draw_silentor used as the source ofmap(), andprint_as_repr()orprint_with()make it printable. Drawing it withtc.drawraisesNotPrintable.labelidentifies the generator to the engine’s shrinker: generators drawing the same shape of value share one. A subclass that sets nolabelof 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(ortc.draw_and_print), never by calling theirdo_drawdirectly, 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
printeras it is drawn. Must draw exactly the same choices asdo_draw().There is no default: a generator that does not implement it cannot print what it draws, and drawing it with
tc.drawraisesNotPrintable.
- map(f: Callable[[T], U]) Generator[U]¶
A generator of
f(value)for eachvaluethis one generates.The mapped value is what the failure report prints.
fruns every time a value is drawn, and shrinking happens on the underlying value, so a mapped generator shrinks towardfof 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
fbuilds from it.fmust return aGenerator; anything else is anInvalidArgument. 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 satisfiespredicate, the test case is rejected as if byTestCase.assume. A filter that rejects most values therefore rejects many test cases, and may fail thefilter_too_muchhealth check: prefer generating the values you want directly (gs.integers(min_value=0)rather thangs.integers().filter(lambda n: n >= 0)). Chained filters combine into one, and filteringsampled_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.printis called asprint(value, printer)with aPrettyPrinterto 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(throughPrettyPrinter.repr), in place of however this generator prints. This makes a subclass that implements onlydo_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
repris 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 ofmap(), or with an empty name, is anInvalidArgument.