Printing values

When a test fails, Hegel replays the minimal failing example and prints every drawn value as a name = value line, laid out by the engine to fit the width of the report:

records = [Record(name='', tags=None, scores={}),
 Record(name='', tags=None, scores={}),
 Record(name='', tags=None, scores={})]

Printing is the generator’s job

A value cannot always print itself usefully: a drawn function has no helpful repr, and some values can only be described after they are used. The generator that drew a value can always describe it, so in Hegel printing is a capability of the generator, not the value. A printable generator draws and prints in one step, in its do_draw_and_print() method, writing to a PrettyPrinter as it goes. TestCase.draw() needs a printable generator, so that the report can say what was drawn; TestCase.draw_silent() accepts any generator and reports nothing.

Every generator Hegel provides is printable:

  • Every leaf generator prints the repr of what it draws: integers, floats, booleans, text and characters, regexes, bytes, dates and times, UUIDs, IP addresses, emails, URLs and grammars.

  • Structural generators print as they draw, element by element and argument by argument: lists(), sets(), dicts(), fixed_dicts(), tuples(), optional(), one_of(), filter(), flat_map(), recursive(), deferred() and builds(). An element’s own printing (a print_with() function, a custom generator) shows up inside its container. They are printable whenever their components are.

  • Value-producing generators print the repr of the finished value: map(), just(), sampled_from(), composite() and the stateful pools. A composite’s inner draws never appear in the report, only the value it returns.

Python has no static types to erase, so a generator keeps its own printing wherever it is passed: there is nothing like the Rust library’s boxed to worry about.

When a draw is not printable

A Generator subclass that implements only do_draw cannot print what it draws. Drawing it with TestCase.draw(), directly or inside a structure, raises NotPrintable on the first test case that reaches it. The fixes, in order of preference:

  • Implement do_draw_and_print (below), so the generator prints itself and gets do_draw for free.

  • print_with(): print a custom representation from a function taking the value and the printer, such as .print_with(lambda value, printer: printer.text(f"make({value.id})")). It is also the way to mask a secret.

  • print_as_repr(): print the drawn value’s repr.

  • print_as_call(): on a map() of a printable generator, print the input instead of the output, as Point((0, 0)).

  • TestCase.draw_silent(): draw without reporting the value, when it is not worth reporting.

print_with and print_as_repr print a finished value: they are escape hatches for generators that do not print themselves, not the way built-in generators print.

Writing a printable generator

A printable generator implements do_draw_and_print. It draws its components with TestCase.draw_and_print(), passing the printer on, and writes its own syntax around them:

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)

tc.draw(gs.lists(Coords(), min_size=1)) then reports xs = [Coord(0, 0)]. When the generator is drawn silently, the same method runs with a printer that prints nothing, and its components are drawn silently too, so it draws the same choices either way.

A generator whose value can only be described after it is drawn opens a deferred region at draw time and hands it to the value, which records into it as it is used:

class Recorder:
    def __init__(self, tc, printer):
        self._tc, self._printer, self._first = tc, printer, True

    def next(self):
        value = self._tc.draw_silent(gs.integers(0, 10))
        if not self._first:
            self._printer.separator()
        self._first = False
        self._printer.repr(value)
        return value


class Recorders(gs.Generator[Recorder]):
    def do_draw_and_print(self, tc, printer):
        printer.begin_group(len("Recorder(["), "Recorder([")
        slot = printer.deferred()
        printer.end_group("])")
        return Recorder(tc, slot)

r = tc.draw(Recorders()) followed by two calls of r.next() reports r = Recorder([0, 0]), in the place where r was drawn.

The printer

PrettyPrinter is the write surface a generator prints through. The engine lays its output out with an Oppen-style pretty-printer: text emits literal text, breakable marks a point that renders as a separator when the enclosing group fits on one line and as a newline plus indentation when it does not, and begin_group / end_group (or the group context manager) delimit the groups those decisions are made over. A combinator that may reject a draw prints each attempt into a speculation and commits only the accepted one.

A Document is a standalone document to print into and render, for trying out or testing printing code outside a test case:

document = hegel.Document(max_width=8)
document.printer.seq("{", "}", [1, 2, 3], lambda p, n: p.repr(n))
assert document.finish() == "{1,\n 2,\n 3}"
class hegel.PrettyPrinter

The write surface onto a region of an engine-side document: what a printable generator’s do_draw_and_print, or a print_with() function, writes a value’s representation to.

The engine lays the document out with an Oppen-style pretty-printer. Output is built from three primitives: text() emits literal text, breakable() marks a point that renders as a separator when the enclosing group fits on one line and as a newline plus indentation when it does not, and begin_group() / end_group() delimit the groups those decisions are made over. repr() prints a value’s repr with its bracket structure recovered, so it wraps like a value printed structurally; group(), seq() and separator() are the conveniences most printing code wants.

A printer is only ever handed out, never constructed by printing code: get one from a Document, or from the test case through TestCase.draw_and_print. A no-op printer (PrettyPrinter.noop()) accepts every call and prints nothing, so a generator runs one code path for silent and printing draws.

classmethod noop() → PrettyPrinter

A printer that discards everything written to it. Drawing through it with TestCase.draw_and_print still needs a printable generator; only TestCase.draw_silent makes a draw silent.

property should_print: bool

Whether output written now would appear anywhere: False for a no-op printer and for a dead region (see deferred()). Guard any work done purely for printing with this.

text(text: str) → None

Emit literal text. Newlines become hard breaks.

repr(value: Any) → None

Print repr(value), reflowed by the engine so it wraps like a value printed structurally. repr is only called when the output will be shown.

reflow(text: str) → None

Emit a one-line representation (a repr), letting the engine recover its bracket structure so it wraps like a value printed structurally. Text that does not parse is emitted verbatim.

breakable(sep: str = ' ') → None

A break point: sep when the enclosing group fits on one line, a newline plus indentation otherwise.

if_break(text: str) → None

Text emitted only when the enclosing group breaks (a trailing comma, say).

hard_break() → None

A newline, whether or not the enclosing group fits.

comment(text: str) → None

Attach a comment to the line currently being written: text renders as `` # text`` at the end of that line, and every group open at this position breaks, since nothing else may share a line with a comment. text must not contain newlines.

begin_group(indent: int, open: str) → None

Open a group: emit open and indent break points inside it by indent columns. Every begin_group needs a matching end_group(); group() pairs them for you.

end_group(close: str) → None

Close the group begin_group() opened, emitting close.

group(open: str, close: str, indent: int | None = None) → Iterator[None]

A group around the body of a with block: open, the body’s output with break points indented by indent columns (default len(open), aligning continuation lines just inside open), then close, even if the body raises. Note the argument order differs from begin_group()’s, so that the indent can default:

with printer.group("Point(", ")"):
    printer.repr(x)
    printer.separator()
    printer.repr(y)
seq(open: str, close: str, items: Iterable[T], print_item: Callable[[PrettyPrinter, T], None]) → None

Print items as a delimited, comma-separated sequence: open, each item as print_item(printer, item) prints it with a separator() between consecutive items, then close. It is laid out inline when it fits, and one item per line aligned just inside open when it does not:

printer.seq("{", "}", [1, 2, 3], lambda p, n: p.repr(n))
separator() → None

The separator between two items of a group: a , followed by a break point that renders as a space when the group fits.

shift_indent(delta: int) → None

Adjust the indentation that later break points apply by delta columns.

speculate() → Speculation

Open a speculative region whose output is kept only if the returned Speculation is committed. This is how printing survives rejection: a generator that may retract a draw (a filter retry, a duplicate collection element) prints each attempt into a speculation and commits only the accepted one.

deferred() → PrettyPrinter

A child region anchored at the current position: whatever the returned printer prints, at any later point and from any thread that owns it, appears here when the document renders, laid out as if it had been printed inline.

This is how a generator prints a value that can only be described after it is drawn: it opens a deferred region at draw time and hands it to the value, which records into it as it is used. A region dies when the document renders, or when a speculation its anchor sat inside is aborted; writes to a dead region are silent no-ops and its should_print is False. A deferred region of a no-op printer is a no-op printer.

class hegel.Speculation

A speculative print region; see PrettyPrinter.speculate(). Print through printer, then commit() to keep the output or abort() to discard it.

Usable as a context manager: leaving the block without a commit aborts the region, so an unwinding draw never leaves partial output behind.

commit() → None

Close the region, keeping its output.

abort() → None

Close the region, discarding its output.

class hegel.Document(max_width: int = DEFAULT_MAX_WIDTH)

One pretty-printed document, laid out to max_width columns: write through printer, then render with finish(). Use it to try out or test printing code outside a test case:

document = hegel.Document(max_width=8)
document.printer.seq("{", "}", [1, 2, 3], lambda p, n: p.repr(n))
assert document.finish() == "{1,\n 2,\n 3}"
printer

The PrettyPrinter writing to this document.

finish() → str

Render everything printed so far, splicing in deferred regions. Regions deferred from this document die once it has rendered.

hegel.pretty_repr(value: Any, max_width: int = DEFAULT_MAX_WIDTH) → str

repr(value) as the engine lays it out, wrapped to fit within max_width columns (default 79): what PrettyPrinter.repr() prints, rendered into a fresh Document.

hegel.pretty_print(value: Any, printer: PrettyPrinter) → None

Print repr(value) through printer, reflowed to fit: the same as printer.repr(value), which is the preferred spelling.