Skip to main content

Module python

Module python 

Source
Expand description

Writing a universe out as Python.

Structs become keyword-only dataclasses and inheritance becomes class inheritance, so a Circle really is a Shape to anything asking. Keyword- only is not a style choice: without it, a dataclass cannot have a field with a default before one without, and a parent with an optional field would stop a child from adding a required one. Making every field keyword-only removes the ordering constraint, so declaration order survives from the universe to the generated class.

Enums are the one place this reaches for TypedDict instead. The wire tags a variant with $tag, which is not a name a dataclass field can have, and describing something other than what actually arrives would defeat the purpose.

§Generics

Anything generic is written with the type parameter syntax of PEP 695 — class Box[T]:, def reverse[T](xs: list[T]), type Swap[A, B] = … — so generated code that declares one needs Python 3.12. Everything else still reads on 3.10. The older way, a module-level TypeVar, cannot say which order an alias takes its parameters in: Swap = tuple[B, A] would take B first, because Python orders them by where they first appear. A bound is written as one, and several bounds are left out with a comment saying so, since Python has no way to say a type must be two things at once.

A variant that carries a generic parameter is a class: a TypedDict made the functional way holds the $tag, and a generic class inheriting from it adds the payload, which is the only way a TypedDict with a $tag in it can be generic.

Structs§

Python
The Python backend.

Functions§

literal
Writes a value as a Python literal.