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

hegel.generators.dates(min_value: date = dt.date.min, max_value: date = dt.date.max) → Generator[date]

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

The bounds default to the whole range datetime supports. Bounds that are not dates (a datetime is not accepted), or min_value > max_value, are an InvalidArgument.

hegel.generators.times(min_value: time = dt.time.min, max_value: time = dt.time.max, *, timezones: Generator[Any] | None = None) → Generator[time]

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

The bounds must be naive. The times are naive too, unless timezones is given: a generator of datetime.tzinfo objects (such as timezones()), one of which is attached to each time.

hegel.generators.datetimes(min_value: datetime = dt.datetime.min, max_value: datetime = dt.datetime.max, *, timezones: Generator[Any] | None = None, allow_imaginary: bool = True) → Generator[datetime]

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

The bounds must be naive, and the datetimes are naive unless timezones is given: a generator of datetime.tzinfo objects (or None), such as timezones(). The drawn timezone is attached to the drawn wall-clock time, so the bounds limit the local time, not the instant. With allow_imaginary=False, a local time that does not exist in its timezone (one skipped by a daylight-saving transition) rejects the test case. fold is never set.

aware = tc.draw(gs.datetimes(timezones=gs.timezones()))

Bounds that are not naive datetimes, min_value > max_value, or a timezone generator producing something other than tzinfo objects are an InvalidArgument.

hegel.generators.timedeltas(min_value: timedelta = dt.timedelta.min, max_value: timedelta = dt.timedelta.max) → Generator[timedelta]

Generate datetime.timedelta objects in [min_value, max_value], inclusive, shrinking toward zero: whole days first, then seconds, then microseconds. The bounds default to the whole range datetime supports.

hegel.generators.timezones(*, no_cache: bool = False) → Generator[tzinfo]

Generate IANA timezones, as zoneinfo.ZoneInfo objects, shrinking toward UTC.

The timezones are those zoneinfo.available_timezones() lists; on a system without a timezone database (Windows, say) install the tzdata package. With no_cache=True each is built with zoneinfo.ZoneInfo.no_cache(), so it is not the same object as ZoneInfo(key).

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.