GitHub

API reference for Module.

A Python module being built (Effect's Codegen.Module).

add_schemas adds schemas, declare allocates a name, define gives it source, add appends source, and imports are written for the bindings the source uses. print and finalize take a snapshot; the module stays open. reserved names are left to the surrounding code, as are keywords and builtins.

Functions

__init__

__init__(reserved=()) -> None
ParameterTypeDescription
reservedIterable[str] = ()
def __init__(self, reserved: Iterable[str] = ()) -> None:
    self._given_reserved = frozenset(reserved)
    self._reserved = RESERVED | self._given_reserved
    self._root = Scope()
    self._names: dict[DeclarationBinding, str] = {}
    self._declarations: dict[DeclarationBinding, _Declaration] = {}
    self._order: list[DeclarationBinding | Batch] = []
    self._imports: dict[tuple[tuple[str, str, str], str, bool], ImportBinding] = {}
    self._provided: dict[tuple[str, str, str], ImportBinding] = {}
    self._side_effects: set[str] = set()
    self._import_order: list[ImportBinding | str | Batch] = []
    self._body: list[Fragment] = []
    self._building = False
    self._schemas = Schemas(
        ModuleNames(self._schema_taken, self._declare_schema, self._side_effect, self._import)
    )

add_schemas

add_schemas(schemas: Mapping[str, Representation], /, *, references: References | None = None, type_only: bool = False) -> Mapping[str, DeclarationBinding]
add_schemas(schemas: Mapping[str, Representation], /, *, references: References | None = None, type_only: bool = False, bindings: MutableMapping[str, DeclarationBinding]) -> Mapping[str, DeclarationBinding]

Declares each schema under its name (with a numeric suffix when that is taken), with the definitions it refers to: X holds the schema and XType its type. type_only writes only the types. Returns each schema's binding by the name given (its type's with type_only); a schema that is the reference of its own name is that reference. A name added before, or a reference defined differently before, raises ValueError.

ParameterTypeDescription
schemas
references= None
type_only= False
bindings= None
@overload
def add_schemas(
    self,
    schemas: Mapping[str, Representation],
    /,
    *,
    references: References | None = None,
    type_only: bool = False,
) -> Mapping[str, DeclarationBinding]: ...
@overload
@deprecated(_BINDINGS_DEPRECATED)
def add_schemas(
    self,
    schemas: Mapping[str, Representation],
    /,
    *,
    references: References | None = None,
    type_only: bool = False,
    bindings: MutableMapping[str, DeclarationBinding],
) -> Mapping[str, DeclarationBinding]: ...
def add_schemas(
    self,
    schemas: Mapping[str, Representation],
    /,
    *,
    references: References | None = None,
    type_only: bool = False,
    bindings: MutableMapping[str, DeclarationBinding] | None = None,
) -> Mapping[str, DeclarationBinding]:
    """Declares each schema under its name (with a numeric suffix when that is
    taken), with the definitions it refers to: ``X`` holds the schema and
    ``XType`` its type. ``type_only`` writes only the types. Returns each
    schema's binding by the name given (its type's with ``type_only``); a schema
    that is the reference of its own name is that reference. A name added before,
    or a reference defined differently before, raises ``ValueError``."""
    batch = self._schemas.add(schemas, references or {}, type_only=type_only)
    self._order.append(batch)
    self._import_order.append(batch)
    added = {
        root.name: root.names.alias if type_only else root.names.value for root in batch.roots
    }
    if bindings is not None:
        warnings.warn(_BINDINGS_DEPRECATED, DeprecationWarning, stacklevel=2)
        bindings.update(added)
    return added

scope

scope(parent=None) -> Scope

A declaration scope nested in parent (the module's own by default).

ParameterTypeDescription
parentScope | None = None

Returns Scope

def scope(self, parent: Scope | None = None) -> Scope:
    """A declaration scope nested in ``parent`` (the module's own by default)."""
    return self._own(parent).nested()

declare

declare(preferred_name, *, exact=False, scope=None) -> DeclarationBinding

A new binding named preferred_name made an identifier, with a numeric suffix when the name is reserved or declared in this scope, an enclosing or a nested one. With exact the name is kept, and one that would change raises ValueError.

ParameterTypeDescription
preferred_namestr
exactbool = False
scopeScope | None = None

Returns DeclarationBinding

def declare(
    self, preferred_name: str, *, exact: bool = False, scope: Scope | None = None
) -> DeclarationBinding:
    """A new binding named ``preferred_name`` made an identifier, with a numeric
    suffix when the name is reserved or declared in this scope, an enclosing or a
    nested one. With ``exact`` the name is kept, and one that would change raises
    ``ValueError``."""
    self._build()
    own = self._own(scope)

    def taken_by(name: str) -> str | None:
        return "it is reserved" if name in self._reserved else own.taken_by(name)

    if exact:
        reason = (
            taken_by(preferred_name)
            if is_identifier(preferred_name)
            else "it is not an identifier"
        )
        if reason is not None:
            raise ValueError(f"Cannot declare exact name {literal(preferred_name)}: {reason}")
        name = preferred_name
    else:
        name = allocate(preferred_name, lambda name: taken_by(name) is not None)
    binding = DeclarationBinding(preferred_name, name)
    own.reserve(name)
    self._names[binding] = name
    return binding

define

define(binding, fragments, dependencies=()) -> Self

Gives binding its source. dependencies are the bindings it reads when it runs: print writes their declarations first.

ParameterTypeDescription
bindingDeclarationBinding
fragmentsSequence[Fragment]
dependenciesSequence[Binding] = ()

Returns Self

def define(
    self,
    binding: DeclarationBinding,
    fragments: Sequence[Fragment],
    dependencies: Sequence[Binding] = (),
) -> Self:
    """Gives ``binding`` its source. ``dependencies`` are the bindings it reads
    when it runs: ``print`` writes their declarations first."""
    if binding not in self._names:
        raise ValueError("Expected a declaration binding owned by this module")
    if binding in self._declarations or self._schemas.owns(binding):
        raise ValueError(f"Duplicate definition: {binding.preferred_name}")
    self._declarations[binding] = _Declaration(binding, tuple(fragments), tuple(dependencies))
    self._order.append(binding)
    return self

add_import

add_import(request) -> Binding

The binding of request; the same request gives the same binding.

ParameterTypeDescription
requestImport

Returns Binding

def add_import(self, request: Import) -> Binding:
    """The binding of ``request``; the same request gives the same binding."""
    self._build()
    key = (import_key(request), request.local, request.type_only)
    known = key in self._imports
    binding = self._import(request)
    if not known:
        self._import_order.append(binding)
    return binding

provide_import

provide_import(request) -> Binding

The binding of an import the surrounding code already makes, under request.local exactly; the module writes no statement for it. A local name already taken raises ValueError.

ParameterTypeDescription
requestImport

Returns Binding

def provide_import(self, request: Import) -> Binding:
    """The binding of an import the surrounding code already makes, under
    ``request.local`` exactly; the module writes no statement for it. A local
    name already taken raises ``ValueError``."""
    self._build()
    key = import_key(request)
    existing = self._provided.get(key)
    if existing is not None and existing.request.local == request.local:
        return existing
    local = request.local
    if existing is not None or local in self._reserved or local in self._root.names():
        raise ValueError(f"Conflicting predefined import: {local}")
    binding = ImportBinding(request)
    self._root.reserve(local)
    self._provided[key] = binding
    return binding

add_side_effect

add_side_effect(module) -> Self

Imports module for its side effects (import module), once, in the order of its first call. The name the statement binds is left to it.

ParameterTypeDescription
modulestr

Returns Self

def add_side_effect(self, module: str) -> Self:
    """Imports ``module`` for its side effects (``import module``), once, in the
    order of its first call. The name the statement binds is left to it."""
    self._build()
    check_module(module, needs_name=True)
    statement, bound = module_statement(module, None)
    if self._side_effect(statement, bound):
        self._import_order.append(statement)
    return self

add

add(fragment) -> Self

Appends fragment after the declarations.

ParameterTypeDescription
fragmentFragment

Returns Self

def add(self, fragment: Fragment) -> Self:
    """Appends ``fragment`` after the declarations."""
    self._build()
    self._body.append(fragment)
    return self

finalize

finalize(roots=()) -> Finalized

Renders a snapshot: declarations after their dependencies, then roots in order. A missing definition or a cycle of dependencies raises ValueError. Later declarations can change import names, so render the whole module again after a change.

ParameterTypeDescription
rootsSequence[Fragment] = ()

Returns Finalized

def finalize(self, roots: Sequence[Fragment] = ()) -> Finalized:
    """Renders a snapshot: declarations after their dependencies, then ``roots``
    in order. A missing definition or a cycle of dependencies raises
    ``ValueError``. Later declarations can change import names, so render the
    whole module again after a change."""
    ordered = self._ordered()
    names: dict[Binding, str] = {**self._names}
    imports: dict[tuple[str, str, str], UsedImport] = {}
    render = self._renderer(names, imports)
    declarations = tuple(
        FinalizedDeclaration(d.binding, tuple(map(render, d.fragments))) for d in ordered
    )
    rendered_roots = tuple(map(render, roots))
    body = tuple(map(render, self._body))
    entries: list[UsedImport | str] = []
    for entry in self._expanded_imports():
        if isinstance(entry, str):
            entries.append(entry)
            continue
        key = import_key(entry.request)
        used = imports.get(key)
        if used is not None and (not used.runtime or not entry.request.type_only):
            entries.append(used)
            del imports[key]
    entries.extend(imports.values())
    annotations = any(d.annotated for d in ordered)
    statements = print_imports(entries, annotations=annotations)
    return Finalized(names, declarations, rendered_roots, statements, body)

print

print() -> str

The module's source: imports, declarations in dependency order, then what add appended. Run it, or check it with pyright.

Returns str

def print(self) -> str:
    """The module's source: imports, declarations in dependency order, then what
    ``add`` appended. Run it, or check it with pyright."""
    if not self._building and not self._schemas.declared():
        _empty()
    output = self.finalize()
    parts = [
        "\n".join(output.imports),
        *(fragment for d in output.declarations for fragment in d.fragments),
        *output.body,
    ]
    return "\n\n".join(part for part in parts if part != "") + "\n"