Skip to content

API¤

The public surface is the top-level wadler_lindig_parts module: every name below is reachable as wadler_lindig_parts.<name>. There is no private-but-documented tier — a name a consumer needs is public, and a name that is public is tested.

For the grammar these functions read, see Format spec grammar; for the vocabulary, see Axes, layouts and markups.

The extension point¤

wadler_lindig_parts.pparts(obj: typing.Any, /, *, markup: str = 'text', **kw: typing.Any) -> tuple[typing.Any, ...] ¤

Decompose an object into a tree of PPart / PGroup fragments.

This is the extension point: register an implementation for your type and it gains every preset, every markup, and the wadler-lindig layout path.

A registered method must accept **kw: the engine forwards the axes it does not itself act on (short_arrays, unit_style, value_spec, ...) to it on every route, wl.pformat included.

wadler_lindig_parts.render_options(obj: typing.Any, /, *, spec: Spec) -> collections.abc.Mapping[str, typing.Any] ¤

Return a type's own wadler_lindig.pformat options for spec.

The extension point for call layout's renderer, as pparts is for product. Register a method for your type to pass options that are not spec words, such as a custom= hook that lays out a value type its own way. It receives the spec because the right options can depend on it: wadler-lindig calls custom= on every object, whatever short_arrays says, so a hook that shortens arrays has to stay out of array.

render asks for them, so repr, str and format under call all get them. A wl.pformat call that reaches the object from outside (as a field of another object) uses the outer call's options instead, since a __pdoc__ cannot change the options it was called with.

spec is keyword-only, so dispatch is on obj alone: a base class and a subclass can each register a method, however they annotate spec, without plum finding them ambiguous. A key the spec already controls raises ValueError (see render). Other keys are not checked: wadler-lindig forwards unknown ones to every __pdoc__ it calls.

Examples¤

from wadler_lindig_parts import parse_spec, render_options dict(render_options(1.0, spec=parse_spec("call"))) {}

wadler_lindig_parts.PPart ¤

One roled fragment of a formatted object.

Parameters¤

role What this fragment is -- "value", "unit", "uncert", "frame", ... The vocabulary is open: a MARKUPS row may override the rendering of a role it knows, and falls back to text for one it does not, so a new role needs no markup change at all. text The plain-text rendering, which doubles as the fallback for any markup with no override for this role. kind "content" -- plain text, escaped and then wrapped. "markup" -- already-rendered markup, wrapped but not escaped. "sep" -- a literal separator, not wrapped; it may offer a line break (see parts_to_doc). Escaped like content, unless the markup has a per-role override for it, which is trusted as markup. doc An optional wadler-lindig document for the fragment. Text-mode layout uses it, so line breaking reaches inside; text stays as the flat fallback, and is what markup layouts use.

Escaping defaults to on so the failure mode is closed: a fragment carrying real markup must say so.

Examples¤

from wadler_lindig_parts import PPart PPart("value", "1.0") PPart(role='value', text='1.0', kind='content', doc=None)

__classdictcell__ = <cell at 0x7fc426a10d00: dict object at 0x7fc4262eae80> class-attribute ¤

Create a new cell object.

contents the contents of the cell. If not specified, the cell will be empty, and further attempts to access its cell_contents attribute will raise a ValueError.

__doc__ = 'One roled fragment of a formatted object.\n\nParameters\n----------\nrole\n What this fragment *is* -- ``"value"``, ``"unit"``, ``"uncert"``,\n ``"frame"``, ... The vocabulary is open: a `MARKUPS` row may override\n the rendering of a role it knows, and falls back to `text` for one it\n does not, so a new role needs no markup change at all.\ntext\n The plain-text rendering, which doubles as the fallback for any markup\n with no override for this role.\nkind\n ``"content"`` -- plain text, escaped and then wrapped.\n ``"markup"`` -- already-rendered markup, wrapped but *not* escaped.\n ``"sep"`` -- a literal separator, not wrapped; it may offer a line\n break (see `parts_to_doc`). Escaped like content, unless the markup\n has a per-role override for it, which is trusted as markup.\ndoc\n An optional wadler-lindig document for the fragment. Text-mode layout\n uses it, so line breaking reaches inside; `text` stays as the flat\n fallback, and is what markup layouts use.\n\nEscaping defaults to on so the failure mode is closed: a fragment carrying\nreal markup must say so.\n\nExamples\n--------\n>>> from wadler_lindig_parts import PPart\n>>> PPart("value", "1.0")\nPPart(role=\'value\', text=\'1.0\', kind=\'content\', doc=None)\n\n' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 90 class-attribute ¤

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('role', 'text', 'kind', 'doc') class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'wadler_lindig_parts.engine' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__orig_bases__ = (<function NamedTuple at 0x7fc4278768d0>,) class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__slots__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

doc = _tuplegetter(3, 'Alias for field number 3') class-attribute ¤

Alias for field number 3

kind = _tuplegetter(2, 'Alias for field number 2') class-attribute ¤

Alias for field number 2

role = _tuplegetter(0, 'Alias for field number 0') class-attribute ¤

Alias for field number 0

text = _tuplegetter(1, 'Alias for field number 1') class-attribute ¤

Alias for field number 1

wadler_lindig_parts.PGroup ¤

A nested run of fragments that lays out as a unit.

A composite embeds a child's fragments by wrapping them in a PGroup, not by splicing them into its own tuple and not by embedding a rendered string:

  • Embedding a string applies the outer markup wrapper once per child, so LaTeX emits nested $...$ and is invalid.
  • Splicing flat loses the grouping boundary. A wadler-lindig group is all-or-nothing, so one flat run means every break point breaks together and a nested quantity's * separators break for no reason.

A PGroup gives each child its own GroupDoc, so inner groups stay inline until they individually have to break, while parts_to_markup flattens the tree and applies its wrapper exactly once at the top.

Examples¤

from wadler_lindig_parts import PGroup, PPart PGroup("child", (PPart("value", "1.0"),)) # doctest: +NORMALIZE_WHITESPACE PGroup(role='child', parts=(PPart(role='value', text='1.0', kind='content', doc=None),))

__classdictcell__ = <cell at 0x7fc426864370: dict object at 0x7fc4251fbf00> class-attribute ¤

Create a new cell object.

contents the contents of the cell. If not specified, the cell will be empty, and further attempts to access its cell_contents attribute will raise a ValueError.

__doc__ = 'A nested run of fragments that lays out as a unit.\n\nA composite embeds a child\'s fragments by wrapping them in a `PGroup`, not\nby splicing them into its own tuple and not by embedding a rendered string:\n\n- Embedding a *string* applies the outer markup wrapper once per child, so\n LaTeX emits nested ``$...$`` and is invalid.\n- Splicing *flat* loses the grouping boundary. A wadler-lindig group is\n all-or-nothing, so one flat run means every break point breaks together\n and a nested quantity\'s ``*`` separators break for no reason.\n\nA `PGroup` gives each child its own ``GroupDoc``, so inner groups stay\ninline until they individually have to break, while `parts_to_markup`\nflattens the tree and applies its wrapper exactly once at the top.\n\nExamples\n--------\n>>> from wadler_lindig_parts import PGroup, PPart\n>>> PGroup("child", (PPart("value", "1.0"),)) # doctest: +NORMALIZE_WHITESPACE\nPGroup(role=\'child\',\n parts=(PPart(role=\'value\', text=\'1.0\', kind=\'content\', doc=None),))\n\n' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 131 class-attribute ¤

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('role', 'parts') class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'wadler_lindig_parts.engine' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__orig_bases__ = (<function NamedTuple at 0x7fc4278768d0>,) class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__slots__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

parts = _tuplegetter(1, 'Alias for field number 1') class-attribute ¤

Alias for field number 1

role = _tuplegetter(0, 'Alias for field number 0') class-attribute ¤

Alias for field number 0

wadler_lindig_parts.doc_part(role: str, doc: AbstractDoc, /, kind: str = 'content') -> PPart ¤

Build a PPart carrying a document, with its flat text alongside.

The engine inserts doc as it is, so text in it must already be escaped for the markup being rendered, as a pvalue method does with markup_table's escape. Only a part's text is escaped for you.

Examples¤

import wadler_lindig as wl from wadler_lindig_parts import doc_part doc_part("value", wl.TextDoc("1.0")).text '1.0'

wadler_lindig_parts.ReprMixin ¤

Derive repr/str/format/IPython reprs/__pdoc__ from pparts.

Declare the layout once as a spec string; it is resolved when the class is created, so a bad spec -- or an alias registered too late -- fails at definition, not on first print::

@dataclass(repr=False)  # repr=True would shadow the mixin
class Version(ReprMixin):
    __repr_spec__ = "bare"

Register pparts for the type; everything else follows. A type whose repr is a constructor expression sets a call spec: a dataclass then gets wadler-lindig's field layout, and any other type keeps an explicit __pdoc__. _repr_html_ and _repr_latex_ lay the fragments out flat, since HTML collapses whitespace and LaTeX math ignores newlines, and they follow the class spec as repr does: a mul type keeps its * in a notebook. When repr is a constructor expression (a call dataclass, or a call type with its own __pdoc__) they return None, so a notebook shows that same expression.

Under a call spec a dataclass's __pdoc__ from this mixin returns None, which tells wadler-lindig to use its field layout. A subclass that overrides __pdoc__ and calls super().__pdoc__() must handle that.

The call behaviour follows the class spec, not the one a caller passes: f"{x:call}" asks the type for its __pdoc__, and a mixin type answers with its constructor form only if its own spec is call.

The registered pparts method must accept **kw (the engine forwards axes such as short_arrays and unit_style on every route). __repr_spec__ is parsed when the class is created; reassigning it later is not re-parsed. width=/indent= in __repr_spec__ apply to repr/str only: wadler_lindig.pformat picks the width when it is called, so __pdoc__ cannot honour them.

__annotations_cache__ = {'__repr_spec__': typing.ClassVar[str], '_repr_spec_parsed': typing.ClassVar[wadler_lindig_parts.engine.Spec]} class-attribute ¤

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__dict__ = mappingproxy({'__module__': 'wadler_lindig_parts.engine', '__firstlineno__': 1352, '__doc__': 'Derive ``repr``/``str``/``format``/IPython reprs/``__pdoc__`` from `pparts`.\n\nDeclare the layout once as a spec string; it is resolved when the *class*\nis created, so a bad spec -- or an alias registered too late -- fails at\ndefinition, not on first print::\n\n @dataclass(repr=False) # repr=True would shadow the mixin\n class Version(ReprMixin):\n __repr_spec__ = "bare"\n\nRegister `pparts` for the type; everything else follows. A type whose\n``repr`` is a *constructor expression* sets a ``call`` spec: a dataclass\nthen gets wadler-lindig\'s field layout, and any other type keeps an\nexplicit ``__pdoc__``. ``_repr_html_`` and ``_repr_latex_`` lay the\nfragments out flat, since HTML collapses whitespace and LaTeX math ignores\nnewlines, and they follow the class spec as ``repr`` does: a ``mul`` type\nkeeps its `` * `` in a notebook. When ``repr`` is a constructor expression\n(a ``call`` dataclass, or a ``call`` type with its own ``__pdoc__``) they\nreturn `None`, so a notebook shows that same expression.\n\nUnder a ``call`` spec a dataclass\'s ``__pdoc__`` from this mixin returns\n`None`, which tells wadler-lindig to use its field layout. A subclass that\noverrides ``__pdoc__`` and calls ``super().__pdoc__()`` must handle that.\n\nThe ``call`` behaviour follows the *class* spec, not the one a caller\npasses: ``f"{x:call}"`` asks the type for its ``__pdoc__``, and a mixin\ntype answers with its constructor form only if its own spec is ``call``.\n\nThe registered `pparts` method must accept ``**kw`` (the engine forwards\naxes such as ``short_arrays`` and ``unit_style`` on every route).\n``__repr_spec__`` is parsed when the class is created; reassigning it\nlater is not re-parsed. ``width=``/``indent=`` in ``__repr_spec__`` apply to\n``repr``/``str`` only: `wadler_lindig.pformat` picks the width when it is\ncalled, so ``__pdoc__`` cannot honour them.\n', '__repr_spec__': 'product', '__init_subclass__': <classmethod(<function ReprMixin.__init_subclass__ at 0x7fc425198880>)>, '__repr__': <function ReprMixin.__repr__ at 0x7fc4251989e0>, '__str__': <function ReprMixin.__str__ at 0x7fc425198b40>, '__format__': <function ReprMixin.__format__ at 0x7fc425198ca0>, '_flat_markup': <function ReprMixin._flat_markup at 0x7fc425198e00>, '_repr_is_constructor': <function ReprMixin._repr_is_constructor at 0x7fc425198f60>, '_repr_html_': <function ReprMixin._repr_html_ at 0x7fc4251990c0>, '_repr_latex_': <function ReprMixin._repr_latex_ at 0x7fc425199220>, '__pdoc__': <function ReprMixin.__pdoc__ at 0x7fc425199380>, '__annotate_func__': <function ReprMixin.__annotate__ at 0x7fc425199430>, '__static_attributes__': (), '__dict__': <attribute '__dict__' of 'ReprMixin' objects>, '__weakref__': <attribute '__weakref__' of 'ReprMixin' objects>, '__annotations_cache__': {'__repr_spec__': typing.ClassVar[str], '_repr_spec_parsed': typing.ClassVar[wadler_lindig_parts.engine.Spec]}}) class-attribute ¤

Read-only proxy of a mapping.

__doc__ = 'Derive ``repr``/``str``/``format``/IPython reprs/``__pdoc__`` from `pparts`.\n\nDeclare the layout once as a spec string; it is resolved when the *class*\nis created, so a bad spec -- or an alias registered too late -- fails at\ndefinition, not on first print::\n\n @dataclass(repr=False) # repr=True would shadow the mixin\n class Version(ReprMixin):\n __repr_spec__ = "bare"\n\nRegister `pparts` for the type; everything else follows. A type whose\n``repr`` is a *constructor expression* sets a ``call`` spec: a dataclass\nthen gets wadler-lindig\'s field layout, and any other type keeps an\nexplicit ``__pdoc__``. ``_repr_html_`` and ``_repr_latex_`` lay the\nfragments out flat, since HTML collapses whitespace and LaTeX math ignores\nnewlines, and they follow the class spec as ``repr`` does: a ``mul`` type\nkeeps its `` * `` in a notebook. When ``repr`` is a constructor expression\n(a ``call`` dataclass, or a ``call`` type with its own ``__pdoc__``) they\nreturn `None`, so a notebook shows that same expression.\n\nUnder a ``call`` spec a dataclass\'s ``__pdoc__`` from this mixin returns\n`None`, which tells wadler-lindig to use its field layout. A subclass that\noverrides ``__pdoc__`` and calls ``super().__pdoc__()`` must handle that.\n\nThe ``call`` behaviour follows the *class* spec, not the one a caller\npasses: ``f"{x:call}"`` asks the type for its ``__pdoc__``, and a mixin\ntype answers with its constructor form only if its own spec is ``call``.\n\nThe registered `pparts` method must accept ``**kw`` (the engine forwards\naxes such as ``short_arrays`` and ``unit_style`` on every route).\n``__repr_spec__`` is parsed when the class is created; reassigning it\nlater is not re-parsed. ``width=``/``indent=`` in ``__repr_spec__`` apply to\n``repr``/``str`` only: `wadler_lindig.pformat` picks the width when it is\ncalled, so ``__pdoc__`` cannot honour them.\n' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 1352 class-attribute ¤

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__module__ = 'wadler_lindig_parts.engine' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__repr_spec__ = 'product' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__static_attributes__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__weakref__ property ¤

list of weak references to the object

__annotate_func__(format) ¤
__format__(format_spec: str) -> str ¤
__init_subclass__(**kw: typing.Any) -> None classmethod ¤
__pdoc__(*, indent: int = 2, **kw: typing.Any) -> wadler_lindig._wadler_lindig.AbstractDoc | None ¤
__repr__() -> str ¤
__str__() -> str ¤

Registration¤

wadler_lindig_parts.Axis ¤

One independent choice a format spec can make.

Parameters¤

name The axis, and the key it occupies in a Spec. keywords Spec word -> the value it sets. Words live in one flat namespace shared by every axis, and must stay pairwise disjoint; register_axis enforces that, which is what lets a keyword run be order-independent with no content-sniffing. default The value when no keyword names this axis. layouts Layout -> a function turning this axis's value into keyword arguments for that layout's renderer. Membership is applicability: an axis applies to exactly the layouts it has an entry for, so naming it under any other layout is an error rather than a silent no-op. free_text The layouts in which this axis's value may instead be arbitrary text -- the trailing run a spec ends with, such as a Python format spec. Empty for a closed axis, which is most of them.

At most one axis may claim free text, and the engine enforces it. That
is not a restriction so much as an observation: the scan rule makes the
trailing run terminal, so there is only one of them to claim.
__classdictcell__ = <cell at 0x7fc42686ce50: dict object at 0x7fc425247e80> class-attribute ¤

Create a new cell object.

contents the contents of the cell. If not specified, the cell will be empty, and further attempts to access its cell_contents attribute will raise a ValueError.

__doc__ = "One independent choice a format spec can make.\n\nParameters\n----------\nname\n The axis, and the key it occupies in a `Spec`.\nkeywords\n Spec word -> the value it sets. Words live in one flat namespace\n shared by every axis, and must stay pairwise disjoint; `register_axis`\n enforces that, which is what lets a keyword run be order-independent\n with no content-sniffing.\ndefault\n The value when no keyword names this axis.\nlayouts\n Layout -> a function turning this axis's value into keyword arguments\n for that layout's renderer. **Membership is applicability**: an axis\n applies to exactly the layouts it has an entry for, so naming it under\n any other layout is an error rather than a silent no-op.\nfree_text\n The layouts in which this axis's value may instead be *arbitrary text*\n -- the trailing run a spec ends with, such as a Python format spec.\n Empty for a closed axis, which is most of them.\n\n At most one axis may claim free text, and the engine enforces it. That\n is not a restriction so much as an observation: the scan rule makes the\n trailing run terminal, so there is only one of them to claim.\n\n" class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 633 class-attribute ¤

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('name', 'keywords', 'default', 'layouts', 'free_text') class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'wadler_lindig_parts.engine' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__orig_bases__ = (<function NamedTuple at 0x7fc4278768d0>,) class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__slots__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

default = _tuplegetter(2, 'Alias for field number 2') class-attribute ¤

Alias for field number 2

free_text = _tuplegetter(4, 'Alias for field number 4') class-attribute ¤

Alias for field number 4

keywords = _tuplegetter(1, 'Alias for field number 1') class-attribute ¤

Alias for field number 1

layouts = _tuplegetter(3, 'Alias for field number 3') class-attribute ¤

Alias for field number 3

name = _tuplegetter(0, 'Alias for field number 0') class-attribute ¤

Alias for field number 0

wadler_lindig_parts.register_axis(axis: Axis, /, *, replace: bool = False) -> Axis ¤

Add an axis to the grammar, rejecting any keyword collision.

Registration is the only way in. A downstream package registering vector_form gets exactly what the built-in axes get -- there is no privileged set. replace=True swaps out an axis of the same name.

wadler_lindig_parts.unregister_axis(name: str) -> None ¤

Remove an axis and its keywords from the grammar (for tests and reloads).

wadler_lindig_parts.register_alias(name: str, expansion: str, /, *, replace: bool = False) -> None ¤

Add a whole-spec shorthand, rejecting any collision.

Both directions are checked, because both are the same mistake: a name that already means something must not quietly start meaning something else. Silently overwriting is how a spec changes meaning without anyone editing the spec. replace=True overwrites an alias deliberately.

wadler_lindig_parts.unregister_alias(name: str) -> None ¤

Remove a whole-spec shorthand.

wadler_lindig_parts.register_markup(name: str, row: collections.abc.Mapping[str, typing.Any], /, *, replace: bool = False) -> None ¤

Add a markup (a MARKUPS row) and make it selectable by spec.

wadler_lindig_parts.unregister_markup(name: str) -> None ¤

Remove a markup added by register_markup.

A test/reload helper: removing a built-in markup (text, html, latex) breaks the product layouts that name it.

The registries¤

wadler_lindig_parts.AXES = mappingproxy({'layout': Axis(name='layout', keywords={'call': 'call', 'product': 'product'}, default='product', layouts={'call': <function <lambda> at 0x7fc42519fc10>, 'product': <function <lambda> at 0x7fc42519fc10>}, free_text=()), 'width': Axis(name='width', keywords=<wadler_lindig_parts.engine._Count object at 0x7fc4253bb230>, default=None, layouts={'call': None, 'product': None}, free_text=()), 'indent': Axis(name='indent', keywords=<wadler_lindig_parts.engine._Count object at 0x7fc4253e6850>, default=None, layouts={'call': None, 'product': None}, free_text=()), 'markup': Axis(name='markup', keywords={'text': 'text', 'html': 'html', 'latex': 'latex'}, default='text', layouts={'product': <function <lambda> at 0x7fc425199bc0>}, free_text=()), 'sep': Axis(name='sep', keywords={'mul': 'mul', 'bare': 'bare'}, default='bare', layouts={'product': <function <lambda> at 0x7fc425199c70>}, free_text=()), 'value': Axis(name='value', keywords={'array': 'array', 'values': 'values', 'type': 'type'}, default='values', layouts={'call': <function <lambda> at 0x7fc425199d20>, 'product': <function _value_product_kwargs at 0x7fc425199b10>}, free_text=('product',))}) module-attribute ¤

Read-only proxy of a mapping.

wadler_lindig_parts.ALIASES = mappingproxy({}) module-attribute ¤

Read-only proxy of a mapping.

wadler_lindig_parts.MARKUPS = mappingproxy({'text': {'_content': '{}', 'wrap': '{}', 'vsep': ', ', 'escape': None, 'bare': ' '}, 'html': {'_content': '<span>{}</span>', 'wrap': '{}', 'vsep': ', ', 'escape': <function escape at 0x7fc42752c510>, 'bare': ' '}, 'latex': {'_content': '{}', 'wrap': '${}$', 'vsep': ',~', 'escape': <function _latex_escape at 0x7fc4251aba00>, 'bare': ' \\, ', 'mul': ' \\; ', 'gap': '\\ ', 'pm': ' \\pm '}}) module-attribute ¤

Read-only proxy of a mapping.

wadler_lindig_parts.REQUIRED_MARKUP_KEYS = ('_content', 'wrap', 'vsep', 'escape') module-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

wadler_lindig_parts.markup_table(markup: str) -> collections.abc.Mapping[str, typing.Any] ¤

Return the MARKUPS row, naming the markup if it is unknown.

Specs¤

wadler_lindig_parts.Spec ¤

A fully resolved format spec: one settled value for every axis.

A mapping rather than a record, so a downstream axis is read exactly like a built-in one (spec["markup"], spec["vector_form"]). Defaults are filled in at parse time, so every registered axis is always present and a reader never has to know which were named.

__abstractmethods__ = frozenset() class-attribute ¤

Build an immutable unordered collection of unique elements.

__doc__ = 'A fully resolved format spec: one settled value for every axis.\n\nA mapping rather than a record, so a downstream axis is read exactly like\na built-in one (``spec["markup"]``, ``spec["vector_form"]``). Defaults are\nfilled in at parse time, so every registered axis is always present and a\nreader never has to know which were named.\n' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 810 class-attribute ¤

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__module__ = 'wadler_lindig_parts.engine' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__orig_bases__ = (collections.abc.Mapping[str, typing.Any],) class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__slots__ = ('_d',) class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = ('_d',) class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__getitem__(key: str) -> typing.Any ¤
__init__(mapping: collections.abc.Mapping[str, typing.Any] | collections.abc.Iterable[tuple[str, typing.Any]] = (), /, **kw: typing.Any) -> None ¤
__iter__() -> collections.abc.Iterator[str] ¤
__len__() -> int ¤
__repr__() -> str ¤
of(**overrides: typing.Any) -> Spec classmethod ¤

Build a resolved spec, defaulting every axis not named.

This is the way to construct one by hand. Taking the defaults from the registry is what keeps a hand-built spec complete once a later axis is registered -- writing the mapping out directly leaves a hole that surfaces only as a KeyError at render time.

Examples¤

from wadler_lindig_parts import Spec, parse_spec

Spec.of(layout="call")["markup"] 'text'

Spec.of() == parse_spec("product") True

wadler_lindig_parts.parse_spec(spec: str, /, *, obj: typing.Any = None) -> Spec ¤

Resolve a format spec into a Spec, or raise ValueError.

The parse is total and strictly left-to-right: split on -, consume tokens while they are keywords (expanding an alias in place), and stop at the first token that is not one. Everything from that token onward -- including any further - -- is the value spec.

That one rule is what keeps the grammar unambiguous once an arbitrary Python format spec is in play. A format spec may contain - itself, as a sign flag ("-.2f") or a fill character ("->10.2f"), and neither can be mistaken for a component boundary, because keywords are only recognised before the value spec begins.

Examples¤

from wadler_lindig_parts import parse_spec

Keywords set their axis; everything omitted keeps its default:

parse_spec("html-bare")["markup"], parse_spec("html-bare")["sep"] ('html', 'bare')

Order among keywords does not matter:

parse_spec("bare-html") == parse_spec("html-bare") True

A trailing value spec becomes the value axis:

parse_spec("mul-.3g")["value"] '.3g'

A value spec keeps its own -, whether leading or embedded:

parse_spec("-.2f")["value"] '-.2f' parse_spec("mul-->10.2f")["value"] '->10.2f'

An alias expands before parsing. This package ships none -- every alias in existence is registered by a consumer -- so one has to be registered to show it:

from wadler_lindig_parts import register_alias, unregister_alias register_alias("loud", "html-mul") parse_spec("loud") == parse_spec("html-mul") True unregister_alias("loud")

wadler_lindig_parts.pspec(obj: typing.Any, spec: str, /, *, width: int = 88) -> str ¤

Implement __format__ for an object the engine knows.

Examples¤

from wadler_lindig_parts import pspec from wadler_lindig_parts.examples import Term

pspec(Term([1.0, 2.0, 3.0], "x"), "mul") '[1.0, 2.0, 3.0] * x'

pspec(Term([1.0, 2.0, 3.0], "x"), "latex") '$[1.0, 2.0, 3.0] \, x$'

A trailing run that is not a keyword is a Python format spec, applied to the value -- and it needs no keyword to accompany it:

pspec(Term(1.234, "x"), ".2f") '1.23 x' pspec(Term(1.234, "x"), "mul-.2f") '1.23 * x'

An empty spec is str:

term = Term([1.0, 2.0, 3.0], "x") pspec(term, "") == str(term) True

wadler_lindig_parts.render(obj: typing.Any, spec: Spec, /, *, width: int = 88, indent: int = 2, **extra: typing.Any) -> str ¤

Render obj according to an already-resolved Spec.

The single rendering entry point: repr, str and __format__ all arrive here, differing only in the Spec they bring.

extra carries renderer arguments that are not grammar axes -- a type's own __pdoc__ knob, say. They stay out of the spec vocabulary, because one word must mean one thing for every type, but still need a route through so a caller's configuration can drive them.

Under call layout a type can also supply its own, by registering render_options. Those may not set a key the spec already controls (width, indent, or an axis's own argument such as short_arrays): that would override what the caller asked for, so it raises. extra comes last and overrides anything.

Examples¤

from wadler_lindig_parts import parse_spec, render from wadler_lindig_parts.examples import Point, Term

render(Term([1.0, 2.0, 3.0], "x"), parse_spec("mul")) '[1.0, 2.0, 3.0] * x'

call layout renders through the object's own __pdoc__, so it reconstructs a type that never registered anything with the engine:

render(Point(1.0, 2.0), parse_spec("call")) 'Point(x=1.0, y=2.0)'

wadler_lindig_parts.bad_spec(obj: typing.Any, spec: str, /, reason: str = '') -> ValueError ¤

Build the one error every rejected spec raises.

wadler_lindig_parts.inert_axes(obj: typing.Any, spec: Spec, rendered: str, /, *, width: int = 88) -> list[str] ¤

Return the axes spec names explicitly that changed nothing.

Asked by experiment rather than introspection: re-render with one axis reset to its default and see whether the output moves. That needs no cooperation from the type, and it sees through composites for free -- if a child consumed the axis the output differs, which is the answer wanted.

Only axes given a non-default value are checked; a default cannot be said to have had no effect. An axis whose two renderings agree really did nothing visible, which is exactly the claim being made.

Rendering¤

wadler_lindig_parts.parts_to_doc(parts: tuple[typing.Any, ...], /, *, indent: int = 2, sep: str | None = None, markup: str = 'text', _top: bool = True) -> AbstractDoc ¤

Build a wadler-lindig document from fragments, in any markup.

Every markup goes through this one path. Wrapper text is emitted zero-width (_invisible), so it reaches the output without counting toward the line width, and HTML and LaTeX break lines exactly where plain text does. _sep_doc says where the break points come from.

Examples¤

from wadler_lindig_parts import PPart, doc_to_str, parts_to_doc

This takes fragments, so the examples give them literally:

parts = ( ... PPart("value", "[1.0, 2.0, 3.0]"), ... PPart("mul", " * ", "sep"), ... PPart("label", "x"), ... ) doc_to_str(parts_to_doc(parts), 88) '[1.0, 2.0, 3.0] * x'

Markup lays out identically, because its wrappers cost nothing -- the break below falls where it would in plain text, not six columns earlier:

print(doc_to_str(parts_to_doc(parts, markup="html"), 12)) [1.0, 2.0, 3.0] * x

wadler_lindig_parts.parts_to_markup(parts: tuple[typing.Any, ...], /, *, markup: str = 'text', sep: str | None = None) -> str ¤

Flatten fragments into one string in markup, applying its wrappers.

The row's wrap is applied once, at the top, so a nested LaTeX rendering has a single $ pair. This is parts_to_doc laid out flat.

Examples¤

from wadler_lindig_parts import PPart, parts_to_markup

parts = ( ... PPart("value", "[1.0, 2.0, 3.0]"), ... PPart("mul", " * ", "sep"), ... PPart("label", "x"), ... ) parts_to_markup(parts, markup="html") '[1.0, 2.0, 3.0] * x'

parts_to_markup(parts, markup="latex") '$[1.0, 2.0, 3.0] \; x$'

sep names the role standing in for mul, so the markup decides how it renders -- a plain space here, \\, in LaTeX:

parts_to_markup(parts, sep="bare") '[1.0, 2.0, 3.0] x'

wadler_lindig_parts.pparts_to_pdoc(obj: typing.Any, /, *, indent: int = 2, sep: str | None = None, markup: str = 'text', **kw: typing.Any) -> AbstractDoc ¤

Return obj's pparts as a wadler-lindig document.

This is what makes a type that only registers pparts work with wl.pformat / wl.pprint: its __pdoc__ is this call.

Examples¤

from wadler_lindig_parts import doc_to_str, pparts_to_pdoc from wadler_lindig_parts.examples import Term doc_to_str(pparts_to_pdoc(Term([1.0, 2.0], "x"))) '[1.0, 2.0] * x'

wadler_lindig_parts.doc_to_str(doc: AbstractDoc, /, width: int = 88) -> str ¤

Lay out a wadler-lindig document at width.

wadler-lindig lays out a document only through wadler_lindig._wadler_lindig.pformat_doc, a private module path that may move between releases. Handing wadler_lindig.pformat an object whose __pdoc__ returns the document reaches the same code through the public API, and is verified to produce identical output.

Examples¤

import wadler_lindig as wl from wadler_lindig_parts import doc_to_str

doc = wl.TextDoc("[1., 2.]") + wl.BreakDoc(" ") + wl.TextDoc("m") doc_to_str(wl.GroupDoc(doc)) '[1., 2.] m'

Narrow enough, and the break is taken:

print(doc_to_str(wl.GroupDoc(doc), 5)) [1., 2.] m

wadler_lindig_parts.math_doc(text: str) -> AbstractDoc ¤

Build a doc for a LaTeX fragment, billing only its visible glyphs.

\mathrm{\frac{m}{s^{2}}} is 24 characters that render as about three columns. Billed in full it pushes the layout tens of columns past the real width, so width= would break a LaTeX line where the same quantity in text or HTML comfortably fits. Control sequences, braces and the sub/superscript markers are emitted zero-width; only literal glyphs count.

A control sequence that renders a glyph of its own -- \odot, \circ -- costs nothing here, so deg bills 0 rather than 1. Under-billing is the benign direction: it lays a line out flat instead of breaking it early.

Examples¤

import wadler_lindig as wl from wadler_lindig_parts import doc_to_str, math_doc

The fragment is reproduced exactly:

frag = r"\mathrm{\frac{m}{s^{2}}}" doc_to_str(math_doc(frag), 10**9) '\mathrm{\frac{m}{s^{2}}}'

...but costs only the three columns it occupies, so this fits in ten where the same text billed in full does not:

def fits(doc): ... grp = wl.GroupDoc(wl.ConcatDoc(doc, wl.BreakDoc(" "), wl.TextDoc("xxxxxx"))) ... return "\n" not in doc_to_str(grp, 10)

fits(math_doc(frag)) True

fits(wl.TextDoc(frag)) False

wadler_lindig_parts.unwrap_math(text: str) -> str ¤

Strip enclosing $...$ from a LaTeX fragment, if it has them.

Strips only when both delimiters are present, so a fragment that arrives unwrapped is returned unchanged. Slicing unconditionally would turn \mathrm{m} into mathrm{m.

A lone "$" is also returned unchanged: it starts and ends with "$", but there is nothing between them to keep.

Examples¤

from wadler_lindig_parts import unwrap_math

unwrap_math(r"$\mathrm{m}$") '\mathrm{m}'

Already unwrapped, so left alone:

unwrap_math(r"\mathrm{m}") '\mathrm{m}'

unwrap_math("$") '$'

wadler_lindig_parts.pvalue(obj: typing.Any, /, *, markup: str = 'text', short_arrays: typing.Any = 'compact', value_spec: str | None = None, **kw: typing.Any) -> AbstractDoc ¤

Render a value as a wadler-lindig document, escaped for markup.

The extension point for how numbers (or anything else a type holds) are shown. Register a method for your value type; the package default below renders through repr / format / wadler_lindig.pdoc.

wadler_lindig_parts.FLAT = 1000000000 module-attribute ¤

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

wadler_lindig_parts.SHORT_ARRAYS = {'array': False, 'values': 'compact', 'type': True} module-attribute ¤

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

Example types¤

The types the documentation demonstrates on. They exist because an example may not import a consumer: unxt depends on this package, so a doctest reaching for unxt.Quantity would be circular. Version and Term register pparts; Point deliberately does not.

wadler_lindig_parts.examples ¤

An example type for the engine's own documentation -- package side.

The engine's docstrings need a type to demonstrate on, and it cannot be a quantity: this module travels to the standalone package, which unxt depends on, so an example reaching back for unxt.Quantity would be circular.

Version is that type. A version number has parts and roles -- a major, a minor, and a separator between them -- which is everything the engine needs to show, and no units anywhere.

Importing this module registers a pparts method for Version, so it is imported for its side effect as much as for the name. That is sound here because the type is defined alongside the method; a module registering behaviour for a type it does not own is the pattern that caused #1008.

Like engine and generic, this imports only the standard library, wadler_lindig, plum and its sibling package-side modules.

__all__ = ('Point', 'Term', 'Version') module-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__cached__ = '/home/runner/work/wadler-lindig-parts/wadler-lindig-parts/src/wadler_lindig_parts/__pycache__/examples.cpython-314.pyc' module-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__doc__ = "An example type for the engine's own documentation -- package side.\n\nThe engine's docstrings need a type to demonstrate on, and it cannot be a\nquantity: this module travels to the standalone package, which `unxt` depends\non, so an example reaching back for `unxt.Quantity` would be circular.\n\n`Version` is that type. A version number has parts and roles -- a major, a\nminor, and a separator between them -- which is everything the engine needs to\nshow, and no units anywhere.\n\nImporting this module registers a `pparts` method for `Version`, so it is\nimported for its side effect as much as for the name. That is sound here\nbecause the type is defined alongside the method; a module registering\nbehaviour for a type it does not own is the pattern that caused #1008.\n\nLike `engine` and `generic`, this imports only the standard library,\n`wadler_lindig`, `plum` and its sibling package-side modules.\n" module-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__file__ = '/home/runner/work/wadler-lindig-parts/wadler-lindig-parts/src/wadler_lindig_parts/examples.py' module-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__name__ = 'wadler_lindig_parts.examples' module-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__package__ = 'wadler_lindig_parts' module-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

Version ¤

A two-part version number, rendered through pparts.

repr=False on the decorator is load-bearing: a generated __repr__ would shadow the one ReprMixin provides, and the shadowing is silent.

Examples¤

from wadler_lindig_parts.examples import Version

Version(2, 1) 2.1

The fragments carry roles, so each markup wraps them its own way:

f"{Version(2, 1):html}" '2.1'

f"{Version(2, 1):latex}" '$2.1$'

__dict__ = mappingproxy({'__module__': 'wadler_lindig_parts.engine', '__firstlineno__': 1352, '__doc__': 'Derive ``repr``/``str``/``format``/IPython reprs/``__pdoc__`` from `pparts`.\n\nDeclare the layout once as a spec string; it is resolved when the *class*\nis created, so a bad spec -- or an alias registered too late -- fails at\ndefinition, not on first print::\n\n @dataclass(repr=False) # repr=True would shadow the mixin\n class Version(ReprMixin):\n __repr_spec__ = "bare"\n\nRegister `pparts` for the type; everything else follows. A type whose\n``repr`` is a *constructor expression* sets a ``call`` spec: a dataclass\nthen gets wadler-lindig\'s field layout, and any other type keeps an\nexplicit ``__pdoc__``. ``_repr_html_`` and ``_repr_latex_`` lay the\nfragments out flat, since HTML collapses whitespace and LaTeX math ignores\nnewlines, and they follow the class spec as ``repr`` does: a ``mul`` type\nkeeps its `` * `` in a notebook. When ``repr`` is a constructor expression\n(a ``call`` dataclass, or a ``call`` type with its own ``__pdoc__``) they\nreturn `None`, so a notebook shows that same expression.\n\nUnder a ``call`` spec a dataclass\'s ``__pdoc__`` from this mixin returns\n`None`, which tells wadler-lindig to use its field layout. A subclass that\noverrides ``__pdoc__`` and calls ``super().__pdoc__()`` must handle that.\n\nThe ``call`` behaviour follows the *class* spec, not the one a caller\npasses: ``f"{x:call}"`` asks the type for its ``__pdoc__``, and a mixin\ntype answers with its constructor form only if its own spec is ``call``.\n\nThe registered `pparts` method must accept ``**kw`` (the engine forwards\naxes such as ``short_arrays`` and ``unit_style`` on every route).\n``__repr_spec__`` is parsed when the class is created; reassigning it\nlater is not re-parsed. ``width=``/``indent=`` in ``__repr_spec__`` apply to\n``repr``/``str`` only: `wadler_lindig.pformat` picks the width when it is\ncalled, so ``__pdoc__`` cannot honour them.\n', '__repr_spec__': 'product', '__init_subclass__': <classmethod(<function ReprMixin.__init_subclass__ at 0x7fc425198880>)>, '__repr__': <function ReprMixin.__repr__ at 0x7fc4251989e0>, '__str__': <function ReprMixin.__str__ at 0x7fc425198b40>, '__format__': <function ReprMixin.__format__ at 0x7fc425198ca0>, '_flat_markup': <function ReprMixin._flat_markup at 0x7fc425198e00>, '_repr_is_constructor': <function ReprMixin._repr_is_constructor at 0x7fc425198f60>, '_repr_html_': <function ReprMixin._repr_html_ at 0x7fc4251990c0>, '_repr_latex_': <function ReprMixin._repr_latex_ at 0x7fc425199220>, '__pdoc__': <function ReprMixin.__pdoc__ at 0x7fc425199380>, '__annotate_func__': <function ReprMixin.__annotate__ at 0x7fc425199430>, '__static_attributes__': (), '__dict__': <attribute '__dict__' of 'ReprMixin' objects>, '__weakref__': <attribute '__weakref__' of 'ReprMixin' objects>, '__annotations_cache__': {'__repr_spec__': typing.ClassVar[str], '_repr_spec_parsed': typing.ClassVar[wadler_lindig_parts.engine.Spec]}}) class-attribute ¤

Read-only proxy of a mapping.

__weakref__ property ¤

list of weak references to the object

__annotations_cache__ = {'major': <class 'int'>, 'minor': <class 'int'>} class-attribute ¤

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__dataclass_fields__ = {'major': Field(name='major',type=<class 'int'>,default=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,default_factory=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,doc=None,_field_type=_FIELD), 'minor': Field(name='minor',type=<class 'int'>,default=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,default_factory=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,doc=None,_field_type=_FIELD)} class-attribute ¤

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__dataclass_params__ = _DataclassParams(init=True,repr=False,eq=True,order=False,unsafe_hash=False,frozen=False,match_args=True,kw_only=False,slots=False,weakref_slot=False) class-attribute ¤
__doc__ = 'A two-part version number, rendered through `pparts`.\n\n``repr=False`` on the decorator is load-bearing: a generated ``__repr__``\nwould shadow the one `ReprMixin` provides, and the shadowing is silent.\n\nExamples\n--------\n>>> from wadler_lindig_parts.examples import Version\n\n>>> Version(2, 1)\n2.1\n\nThe fragments carry roles, so each markup wraps them its own way:\n\n>>> f"{Version(2, 1):html}"\n\'<span>2</span>.<span>1</span>\'\n\n>>> f"{Version(2, 1):latex}"\n\'$2.1$\'\n\n' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 29 class-attribute ¤

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('major', 'minor') class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'wadler_lindig_parts.examples' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__repr_spec__ = 'bare' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__static_attributes__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__annotate_func__(format) ¤
__format__(format_spec: str) -> str ¤
__init_subclass__(**kw: typing.Any) -> None classmethod ¤
__pdoc__(*, indent: int = 2, **kw: typing.Any) -> wadler_lindig._wadler_lindig.AbstractDoc | None ¤
__repr__() -> str ¤
__str__() -> str ¤
__eq__(other) ¤
__init__(major: int, minor: int) -> None ¤
Term ¤

A coefficient and a symbol, joined by a product separator.

The engine is built for values that read as <payload> <operator> <label>, and a quantity is only the most familiar one. Term is that shape without units: it carries a mul separator, so it can demonstrate the sep axis, and its coefficient may be a sequence, so it can demonstrate a line break at a narrow width.

__dict__ = mappingproxy({'__module__': 'wadler_lindig_parts.engine', '__firstlineno__': 1352, '__doc__': 'Derive ``repr``/``str``/``format``/IPython reprs/``__pdoc__`` from `pparts`.\n\nDeclare the layout once as a spec string; it is resolved when the *class*\nis created, so a bad spec -- or an alias registered too late -- fails at\ndefinition, not on first print::\n\n @dataclass(repr=False) # repr=True would shadow the mixin\n class Version(ReprMixin):\n __repr_spec__ = "bare"\n\nRegister `pparts` for the type; everything else follows. A type whose\n``repr`` is a *constructor expression* sets a ``call`` spec: a dataclass\nthen gets wadler-lindig\'s field layout, and any other type keeps an\nexplicit ``__pdoc__``. ``_repr_html_`` and ``_repr_latex_`` lay the\nfragments out flat, since HTML collapses whitespace and LaTeX math ignores\nnewlines, and they follow the class spec as ``repr`` does: a ``mul`` type\nkeeps its `` * `` in a notebook. When ``repr`` is a constructor expression\n(a ``call`` dataclass, or a ``call`` type with its own ``__pdoc__``) they\nreturn `None`, so a notebook shows that same expression.\n\nUnder a ``call`` spec a dataclass\'s ``__pdoc__`` from this mixin returns\n`None`, which tells wadler-lindig to use its field layout. A subclass that\noverrides ``__pdoc__`` and calls ``super().__pdoc__()`` must handle that.\n\nThe ``call`` behaviour follows the *class* spec, not the one a caller\npasses: ``f"{x:call}"`` asks the type for its ``__pdoc__``, and a mixin\ntype answers with its constructor form only if its own spec is ``call``.\n\nThe registered `pparts` method must accept ``**kw`` (the engine forwards\naxes such as ``short_arrays`` and ``unit_style`` on every route).\n``__repr_spec__`` is parsed when the class is created; reassigning it\nlater is not re-parsed. ``width=``/``indent=`` in ``__repr_spec__`` apply to\n``repr``/``str`` only: `wadler_lindig.pformat` picks the width when it is\ncalled, so ``__pdoc__`` cannot honour them.\n', '__repr_spec__': 'product', '__init_subclass__': <classmethod(<function ReprMixin.__init_subclass__ at 0x7fc425198880>)>, '__repr__': <function ReprMixin.__repr__ at 0x7fc4251989e0>, '__str__': <function ReprMixin.__str__ at 0x7fc425198b40>, '__format__': <function ReprMixin.__format__ at 0x7fc425198ca0>, '_flat_markup': <function ReprMixin._flat_markup at 0x7fc425198e00>, '_repr_is_constructor': <function ReprMixin._repr_is_constructor at 0x7fc425198f60>, '_repr_html_': <function ReprMixin._repr_html_ at 0x7fc4251990c0>, '_repr_latex_': <function ReprMixin._repr_latex_ at 0x7fc425199220>, '__pdoc__': <function ReprMixin.__pdoc__ at 0x7fc425199380>, '__annotate_func__': <function ReprMixin.__annotate__ at 0x7fc425199430>, '__static_attributes__': (), '__dict__': <attribute '__dict__' of 'ReprMixin' objects>, '__weakref__': <attribute '__weakref__' of 'ReprMixin' objects>, '__annotations_cache__': {'__repr_spec__': typing.ClassVar[str], '_repr_spec_parsed': typing.ClassVar[wadler_lindig_parts.engine.Spec]}}) class-attribute ¤

Read-only proxy of a mapping.

__weakref__ property ¤

list of weak references to the object

__annotations_cache__ = {'coeff': <class 'object'>, 'symbol': <class 'str'>} class-attribute ¤

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__dataclass_fields__ = {'coeff': Field(name='coeff',type=<class 'object'>,default=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,default_factory=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,doc=None,_field_type=_FIELD), 'symbol': Field(name='symbol',type=<class 'str'>,default=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,default_factory=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,doc=None,_field_type=_FIELD)} class-attribute ¤

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__dataclass_params__ = _DataclassParams(init=True,repr=False,eq=True,order=False,unsafe_hash=False,frozen=False,match_args=True,kw_only=False,slots=False,weakref_slot=False) class-attribute ¤
__doc__ = 'A coefficient and a symbol, joined by a product separator.\n\nThe engine is built for values that read as ``<payload> <operator>\n<label>``, and a quantity is only the most familiar one. `Term` is that\nshape without units: it carries a ``mul`` separator, so it can demonstrate\nthe ``sep`` axis, and its coefficient may be a sequence, so it can\ndemonstrate a line break at a narrow width.\n' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 87 class-attribute ¤

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('coeff', 'symbol') class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'wadler_lindig_parts.examples' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__repr_spec__ = 'mul' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__static_attributes__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__annotate_func__(format) ¤
__format__(format_spec: str) -> str ¤
__init_subclass__(**kw: typing.Any) -> None classmethod ¤
__pdoc__(*, indent: int = 2, **kw: typing.Any) -> wadler_lindig._wadler_lindig.AbstractDoc | None ¤
__repr__() -> str ¤
__str__() -> str ¤
__eq__(other) ¤
__init__(coeff: object, symbol: str) -> None ¤
Point ¤

A plain dataclass: no ReprMixin, no registered pparts.

call layout renders through an object's own __pdoc__, and a dataclass gets a usable one from wadler_lindig for free. So this type demonstrates that the call form reconstructs a value without the type having told the engine anything -- which is the point of routing repr that way rather than building it from fragments.

__annotations_cache__ = {'x': <class 'float'>, 'y': <class 'float'>} class-attribute ¤

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__dataclass_fields__ = {'x': Field(name='x',type=<class 'float'>,default=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,default_factory=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,doc=None,_field_type=_FIELD), 'y': Field(name='y',type=<class 'float'>,default=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,default_factory=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,doc=None,_field_type=_FIELD)} class-attribute ¤

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False,match_args=True,kw_only=False,slots=False,weakref_slot=False) class-attribute ¤
__dict__ = mappingproxy({'__module__': 'wadler_lindig_parts.examples', '__firstlineno__': 114, '__doc__': "A plain dataclass: no `ReprMixin`, no registered `pparts`.\n\n`call` layout renders through an object's own ``__pdoc__``, and a\ndataclass gets a usable one from `wadler_lindig` for free. So this type\ndemonstrates that the ``call`` form reconstructs a value without the type\nhaving told the engine anything -- which is the point of routing ``repr``\nthat way rather than building it from fragments.\n", '__annotate_func__': <function Point.__annotate__ at 0x7fc42519ac40>, '__static_attributes__': (), '__dict__': <attribute '__dict__' of 'Point' objects>, '__weakref__': <attribute '__weakref__' of 'Point' objects>, '__dataclass_params__': _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False,match_args=True,kw_only=False,slots=False,weakref_slot=False), '__annotations_cache__': {'x': <class 'float'>, 'y': <class 'float'>}, '__dataclass_fields__': {'x': Field(name='x',type=<class 'float'>,default=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,default_factory=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,doc=None,_field_type=_FIELD), 'y': Field(name='y',type=<class 'float'>,default=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,default_factory=<dataclasses._MISSING_TYPE object at 0x7fc4275096a0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,doc=None,_field_type=_FIELD)}, '__replace__': <function _replace at 0x7fc42752c3b0>, '__hash__': None, '__init__': <function Point.__init__ at 0x7fc42519ada0>, '__repr__': <function Point.__repr__ at 0x7fc42519b060>, '__eq__': <function Point.__eq__ at 0x7fc42519af00>, '__match_args__': ('x', 'y')}) class-attribute ¤

Read-only proxy of a mapping.

__doc__ = "A plain dataclass: no `ReprMixin`, no registered `pparts`.\n\n`call` layout renders through an object's own ``__pdoc__``, and a\ndataclass gets a usable one from `wadler_lindig` for free. So this type\ndemonstrates that the ``call`` form reconstructs a value without the type\nhaving told the engine anything -- which is the point of routing ``repr``\nthat way rather than building it from fragments.\n" class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 114 class-attribute ¤

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('x', 'y') class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'wadler_lindig_parts.examples' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__static_attributes__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__weakref__ property ¤

list of weak references to the object

__annotate_func__(format) ¤
__eq__(other) ¤
__init__(x: float, y: float) -> None ¤
__repr__() ¤
PPart ¤

One roled fragment of a formatted object.

Parameters¤

role What this fragment is -- "value", "unit", "uncert", "frame", ... The vocabulary is open: a MARKUPS row may override the rendering of a role it knows, and falls back to text for one it does not, so a new role needs no markup change at all. text The plain-text rendering, which doubles as the fallback for any markup with no override for this role. kind "content" -- plain text, escaped and then wrapped. "markup" -- already-rendered markup, wrapped but not escaped. "sep" -- a literal separator, not wrapped; it may offer a line break (see parts_to_doc). Escaped like content, unless the markup has a per-role override for it, which is trusted as markup. doc An optional wadler-lindig document for the fragment. Text-mode layout uses it, so line breaking reaches inside; text stays as the flat fallback, and is what markup layouts use.

Escaping defaults to on so the failure mode is closed: a fragment carrying real markup must say so.

Examples¤

from wadler_lindig_parts import PPart PPart("value", "1.0") PPart(role='value', text='1.0', kind='content', doc=None)

__classdictcell__ = <cell at 0x7fc426a10d00: dict object at 0x7fc4262eae80> class-attribute ¤

Create a new cell object.

contents the contents of the cell. If not specified, the cell will be empty, and further attempts to access its cell_contents attribute will raise a ValueError.

__doc__ = 'One roled fragment of a formatted object.\n\nParameters\n----------\nrole\n What this fragment *is* -- ``"value"``, ``"unit"``, ``"uncert"``,\n ``"frame"``, ... The vocabulary is open: a `MARKUPS` row may override\n the rendering of a role it knows, and falls back to `text` for one it\n does not, so a new role needs no markup change at all.\ntext\n The plain-text rendering, which doubles as the fallback for any markup\n with no override for this role.\nkind\n ``"content"`` -- plain text, escaped and then wrapped.\n ``"markup"`` -- already-rendered markup, wrapped but *not* escaped.\n ``"sep"`` -- a literal separator, not wrapped; it may offer a line\n break (see `parts_to_doc`). Escaped like content, unless the markup\n has a per-role override for it, which is trusted as markup.\ndoc\n An optional wadler-lindig document for the fragment. Text-mode layout\n uses it, so line breaking reaches inside; `text` stays as the flat\n fallback, and is what markup layouts use.\n\nEscaping defaults to on so the failure mode is closed: a fragment carrying\nreal markup must say so.\n\nExamples\n--------\n>>> from wadler_lindig_parts import PPart\n>>> PPart("value", "1.0")\nPPart(role=\'value\', text=\'1.0\', kind=\'content\', doc=None)\n\n' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 90 class-attribute ¤

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('role', 'text', 'kind', 'doc') class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'wadler_lindig_parts.engine' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__orig_bases__ = (<function NamedTuple at 0x7fc4278768d0>,) class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__slots__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

doc = _tuplegetter(3, 'Alias for field number 3') class-attribute ¤

Alias for field number 3

kind = _tuplegetter(2, 'Alias for field number 2') class-attribute ¤

Alias for field number 2

role = _tuplegetter(0, 'Alias for field number 0') class-attribute ¤

Alias for field number 0

text = _tuplegetter(1, 'Alias for field number 1') class-attribute ¤

Alias for field number 1

ReprMixin ¤

Derive repr/str/format/IPython reprs/__pdoc__ from pparts.

Declare the layout once as a spec string; it is resolved when the class is created, so a bad spec -- or an alias registered too late -- fails at definition, not on first print::

@dataclass(repr=False)  # repr=True would shadow the mixin
class Version(ReprMixin):
    __repr_spec__ = "bare"

Register pparts for the type; everything else follows. A type whose repr is a constructor expression sets a call spec: a dataclass then gets wadler-lindig's field layout, and any other type keeps an explicit __pdoc__. _repr_html_ and _repr_latex_ lay the fragments out flat, since HTML collapses whitespace and LaTeX math ignores newlines, and they follow the class spec as repr does: a mul type keeps its * in a notebook. When repr is a constructor expression (a call dataclass, or a call type with its own __pdoc__) they return None, so a notebook shows that same expression.

Under a call spec a dataclass's __pdoc__ from this mixin returns None, which tells wadler-lindig to use its field layout. A subclass that overrides __pdoc__ and calls super().__pdoc__() must handle that.

The call behaviour follows the class spec, not the one a caller passes: f"{x:call}" asks the type for its __pdoc__, and a mixin type answers with its constructor form only if its own spec is call.

The registered pparts method must accept **kw (the engine forwards axes such as short_arrays and unit_style on every route). __repr_spec__ is parsed when the class is created; reassigning it later is not re-parsed. width=/indent= in __repr_spec__ apply to repr/str only: wadler_lindig.pformat picks the width when it is called, so __pdoc__ cannot honour them.

__annotations_cache__ = {'__repr_spec__': typing.ClassVar[str], '_repr_spec_parsed': typing.ClassVar[wadler_lindig_parts.engine.Spec]} class-attribute ¤

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__dict__ = mappingproxy({'__module__': 'wadler_lindig_parts.engine', '__firstlineno__': 1352, '__doc__': 'Derive ``repr``/``str``/``format``/IPython reprs/``__pdoc__`` from `pparts`.\n\nDeclare the layout once as a spec string; it is resolved when the *class*\nis created, so a bad spec -- or an alias registered too late -- fails at\ndefinition, not on first print::\n\n @dataclass(repr=False) # repr=True would shadow the mixin\n class Version(ReprMixin):\n __repr_spec__ = "bare"\n\nRegister `pparts` for the type; everything else follows. A type whose\n``repr`` is a *constructor expression* sets a ``call`` spec: a dataclass\nthen gets wadler-lindig\'s field layout, and any other type keeps an\nexplicit ``__pdoc__``. ``_repr_html_`` and ``_repr_latex_`` lay the\nfragments out flat, since HTML collapses whitespace and LaTeX math ignores\nnewlines, and they follow the class spec as ``repr`` does: a ``mul`` type\nkeeps its `` * `` in a notebook. When ``repr`` is a constructor expression\n(a ``call`` dataclass, or a ``call`` type with its own ``__pdoc__``) they\nreturn `None`, so a notebook shows that same expression.\n\nUnder a ``call`` spec a dataclass\'s ``__pdoc__`` from this mixin returns\n`None`, which tells wadler-lindig to use its field layout. A subclass that\noverrides ``__pdoc__`` and calls ``super().__pdoc__()`` must handle that.\n\nThe ``call`` behaviour follows the *class* spec, not the one a caller\npasses: ``f"{x:call}"`` asks the type for its ``__pdoc__``, and a mixin\ntype answers with its constructor form only if its own spec is ``call``.\n\nThe registered `pparts` method must accept ``**kw`` (the engine forwards\naxes such as ``short_arrays`` and ``unit_style`` on every route).\n``__repr_spec__`` is parsed when the class is created; reassigning it\nlater is not re-parsed. ``width=``/``indent=`` in ``__repr_spec__`` apply to\n``repr``/``str`` only: `wadler_lindig.pformat` picks the width when it is\ncalled, so ``__pdoc__`` cannot honour them.\n', '__repr_spec__': 'product', '__init_subclass__': <classmethod(<function ReprMixin.__init_subclass__ at 0x7fc425198880>)>, '__repr__': <function ReprMixin.__repr__ at 0x7fc4251989e0>, '__str__': <function ReprMixin.__str__ at 0x7fc425198b40>, '__format__': <function ReprMixin.__format__ at 0x7fc425198ca0>, '_flat_markup': <function ReprMixin._flat_markup at 0x7fc425198e00>, '_repr_is_constructor': <function ReprMixin._repr_is_constructor at 0x7fc425198f60>, '_repr_html_': <function ReprMixin._repr_html_ at 0x7fc4251990c0>, '_repr_latex_': <function ReprMixin._repr_latex_ at 0x7fc425199220>, '__pdoc__': <function ReprMixin.__pdoc__ at 0x7fc425199380>, '__annotate_func__': <function ReprMixin.__annotate__ at 0x7fc425199430>, '__static_attributes__': (), '__dict__': <attribute '__dict__' of 'ReprMixin' objects>, '__weakref__': <attribute '__weakref__' of 'ReprMixin' objects>, '__annotations_cache__': {'__repr_spec__': typing.ClassVar[str], '_repr_spec_parsed': typing.ClassVar[wadler_lindig_parts.engine.Spec]}}) class-attribute ¤

Read-only proxy of a mapping.

__doc__ = 'Derive ``repr``/``str``/``format``/IPython reprs/``__pdoc__`` from `pparts`.\n\nDeclare the layout once as a spec string; it is resolved when the *class*\nis created, so a bad spec -- or an alias registered too late -- fails at\ndefinition, not on first print::\n\n @dataclass(repr=False) # repr=True would shadow the mixin\n class Version(ReprMixin):\n __repr_spec__ = "bare"\n\nRegister `pparts` for the type; everything else follows. A type whose\n``repr`` is a *constructor expression* sets a ``call`` spec: a dataclass\nthen gets wadler-lindig\'s field layout, and any other type keeps an\nexplicit ``__pdoc__``. ``_repr_html_`` and ``_repr_latex_`` lay the\nfragments out flat, since HTML collapses whitespace and LaTeX math ignores\nnewlines, and they follow the class spec as ``repr`` does: a ``mul`` type\nkeeps its `` * `` in a notebook. When ``repr`` is a constructor expression\n(a ``call`` dataclass, or a ``call`` type with its own ``__pdoc__``) they\nreturn `None`, so a notebook shows that same expression.\n\nUnder a ``call`` spec a dataclass\'s ``__pdoc__`` from this mixin returns\n`None`, which tells wadler-lindig to use its field layout. A subclass that\noverrides ``__pdoc__`` and calls ``super().__pdoc__()`` must handle that.\n\nThe ``call`` behaviour follows the *class* spec, not the one a caller\npasses: ``f"{x:call}"`` asks the type for its ``__pdoc__``, and a mixin\ntype answers with its constructor form only if its own spec is ``call``.\n\nThe registered `pparts` method must accept ``**kw`` (the engine forwards\naxes such as ``short_arrays`` and ``unit_style`` on every route).\n``__repr_spec__`` is parsed when the class is created; reassigning it\nlater is not re-parsed. ``width=``/``indent=`` in ``__repr_spec__`` apply to\n``repr``/``str`` only: `wadler_lindig.pformat` picks the width when it is\ncalled, so ``__pdoc__`` cannot honour them.\n' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 1352 class-attribute ¤

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__module__ = 'wadler_lindig_parts.engine' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__repr_spec__ = 'product' class-attribute ¤

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__static_attributes__ = () class-attribute ¤

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__weakref__ property ¤

list of weak references to the object

__annotate_func__(format) ¤
__format__(format_spec: str) -> str ¤
__init_subclass__(**kw: typing.Any) -> None classmethod ¤
__pdoc__(*, indent: int = 2, **kw: typing.Any) -> wadler_lindig._wadler_lindig.AbstractDoc | None ¤
__repr__() -> str ¤
__str__() -> str ¤
doc_part(role: str, doc: AbstractDoc, /, kind: str = 'content') -> PPart ¤

Build a PPart carrying a document, with its flat text alongside.

The engine inserts doc as it is, so text in it must already be escaped for the markup being rendered, as a pvalue method does with markup_table's escape. Only a part's text is escaped for you.

Examples¤

import wadler_lindig as wl from wadler_lindig_parts import doc_part doc_part("value", wl.TextDoc("1.0")).text '1.0'

pparts(obj: typing.Any, /, *, markup: str = 'text', **kw: typing.Any) -> tuple[typing.Any, ...] ¤

Decompose an object into a tree of PPart / PGroup fragments.

This is the extension point: register an implementation for your type and it gains every preset, every markup, and the wadler-lindig layout path.

A registered method must accept **kw: the engine forwards the axes it does not itself act on (short_arrays, unit_style, value_spec, ...) to it on every route, wl.pformat included.

pparts_term(obj: typing.Any, /, *, markup: str = 'text', **kw: typing.Any) -> tuple[typing.Any, ...] ¤

Decompose an object into a tree of PPart / PGroup fragments.

This is the extension point: register an implementation for your type and it gains every preset, every markup, and the wadler-lindig layout path.

A registered method must accept **kw: the engine forwards the axes it does not itself act on (short_arrays, unit_style, value_spec, ...) to it on every route, wl.pformat included.

pparts_version(obj: typing.Any, /, *, markup: str = 'text', **kw: typing.Any) -> tuple[typing.Any, ...] ¤

Decompose an object into a tree of PPart / PGroup fragments.

This is the extension point: register an implementation for your type and it gains every preset, every markup, and the wadler-lindig layout path.

A registered method must accept **kw: the engine forwards the axes it does not itself act on (short_arrays, unit_style, value_spec, ...) to it on every route, wl.pformat included.

pvalue(obj: typing.Any, /, *, markup: str = 'text', short_arrays: typing.Any = 'compact', value_spec: str | None = None, **kw: typing.Any) -> AbstractDoc ¤

Render a value as a wadler-lindig document, escaped for markup.

The extension point for how numbers (or anything else a type holds) are shown. Register a method for your value type; the package default below renders through repr / format / wadler_lindig.pdoc.