API orientation
AssignmentandCodeBlockStructured top-level source items.
generate_python_source(obj, header="", clean_mode=False, *, context=None)Generate complete executable source and required imports. A caller-supplied
FormatContextis retained across both render passes and owns clean mode.to_source(value, context=None)Format one value into a
SourceFragment.SourceFormatterNominal extension point. Subclasses implement
can_formatandformat; application-specific formatters register without changing pycodify core.resolve_importsResolve import requirements and aliases for colliding names.
FormatContextandSourceFragmentImmutable typed formatting state and output records.
FormatContextmay carry exact-typeextensionsand exposes them throughextension(type).
The canonical import surface is pycodify.__all__.
Public API
- class pycodify.FormatContext(indent: int = 0, clean_mode: bool = False, name_mappings: ~collections.abc.Mapping[~typing.Tuple[str, str], str] = <factory>, extensions: ~collections.abc.Mapping[type[object], object] = <factory>)[source]
Context passed through serialization.
- indented() FormatContext[source]
- class pycodify.SourceFormatter[source]
Formats a value to Python source code.
- abstractmethod can_format(value: Any) bool[source]
Return True if this formatter handles this value type.
- abstractmethod format(value: Any, context: FormatContext) SourceFragment[source]
Format value to Python source, returning code and required imports.
- classmethod register(formatter: SourceFormatter) None[source]
Register a virtual subclass of an ABC.
Returns the subclass, to allow usage as a class decorator.
- classmethod get_formatter(value: Any) SourceFormatter[source]
- class pycodify.SourceFragment(code: str, imports: FrozenSet[Tuple[str, str]] = frozenset({}))[source]
Result of serializing a value to Python source.
- pycodify.generate_python_source(obj: Any, header: str = '', clean_mode: bool = False, *, context: FormatContext | None = None) str[source]
Generate complete Python source with imports.
- pycodify.resolve_imports(imports: FrozenSet[Tuple[str, str]] | Iterable[Tuple[str, str]]) Tuple[List[str], Dict[Tuple[str, str], str]][source]
Resolve import collisions and generate import lines.
- pycodify.to_source(value: Any, ctx: FormatContext | None = None) SourceFragment[source]
Convert any value to Python source code.