Python modules built from bindings and code fragments (Effect's Codegen).
Module builds a module from named schemas (add_schemas, which replaces
representation.to_code_document followed by to_code_module) and declarations:
declare allocates a name, define gives it source made with code, join,
indent and literal, and the bindings of import_namespace / import_named
become import statements when used. Names are allocated so nothing shadows a keyword, a
builtin, a reserved name or another declaration; strings are written unchanged.
Python spellings of Effect's: ES namespace and named imports are import m as X
and from m import x, a type-only import goes under if TYPE_CHECKING:,
indent indents by four spaces, literal writes Python literals and
doc_comment a docstring. Python has no default export, import attributes or
object-literal keys, so importDefault, attributes and propertyKey have no
counterpart.
Types#
| Type | Definition | Description |
|---|---|---|
CodeHole | type CodeHole = Fragment | int | float | Sequence[CodeHole] | Literal[False] | None | |
Fragment | type Fragment = str | Binding | Parts | Deferred | |
Render | type Render = Callable[[Fragment], str] | |
Import | type Import = NamespaceImport | NamedImport |
Classes#
Functions#
code#
code(*values) -> FragmentSource text and bindings, concatenated without resolving names
(Effect's code template: code("x = ", binding)). Strings go in as
written, numbers as str writes them, sequences item by item, and
None and False as nothing.
| Parameter | Type | Description |
|---|---|---|
values | CodeHole = () |
Returns Fragment
def code(*values: CodeHole) -> Fragment:
"""Source text and bindings, concatenated without resolving names
(Effect's ``code`` template: ``code("x = ", binding)``). Strings go in as
written, numbers as ``str`` writes them, sequences item by item, and
``None`` and ``False`` as nothing."""
parts: list[Fragment] = []
for value in values:
_append(value, parts)
return Parts(tuple(parts))deferred#
deferred(render) -> FragmentSource built while the module renders: render gets a function that
renders a fragment with the module's names. A fragment shared in several
places renders once per finalize.
| Parameter | Type | Description |
|---|---|---|
render | Callable[[Render], str] |
Returns Fragment
def deferred(render: Callable[[Render], str]) -> Fragment:
"""Source built while the module renders: ``render`` gets a function that
renders a fragment with the module's names. A fragment shared in several
places renders once per ``finalize``."""
return Deferred(render)doc_comment#
doc_comment(text) -> strtext as a docstring statement ending in a newline (Effect's JSDoc
docComment), or "" when it has no text. Put it first in the body it
documents; backslashes and quotes that would end it are escaped.
| Parameter | Type | Description |
|---|---|---|
text | str | Sequence[str] |
Returns str
def doc_comment(text: str | Sequence[str]) -> str:
"""``text`` as a docstring statement ending in a newline (Effect's JSDoc
``docComment``), or ``""`` when it has no text. Put it first in the body it
documents; backslashes and quotes that would end it are escaped."""
given = [text] if isinstance(text, str) else text
lines = [
_CLOSING_QUOTE.sub('\\\\"', "".join(map(_escape, line.rstrip())))
for entry in given
for line in _LINE_BREAK.split(entry)
]
while lines and lines[0] == "":
lines.pop(0)
while lines and lines[-1] == "":
lines.pop()
if not lines:
return ""
if len(lines) == 1:
return f'"""{lines[0]}"""\n'
return '"""' + "\n".join(lines) + '\n"""\n'indent#
indent(content) -> Fragmentcontent with every nonempty line after the first indented by four spaces.
| Parameter | Type | Description |
|---|---|---|
content | CodeHole |
Returns Fragment
def indent(content: CodeHole) -> Fragment:
"""``content`` with every nonempty line after the first indented by four spaces."""
fragment = code(content)
return Deferred(lambda render: _NONEMPTY_LINE.sub("\n ", render(fragment)))join#
join(values, separator) -> Fragmentvalues with separator between each two.
| Parameter | Type | Description |
|---|---|---|
values | Sequence[CodeHole] | |
separator | str |
Returns Fragment
def join(values: Sequence[CodeHole], separator: str) -> Fragment:
"""``values`` with ``separator`` between each two."""
parts: list[Fragment] = []
for index, value in enumerate(values):
if index > 0:
parts.append(separator)
_append(value, parts)
return Parts(tuple(parts))literal#
literal(value) -> strvalue as a Python literal: strings in double quotes, float("nan")
and float("inf") for the floats without one, and -0.0 kept.
| Parameter | Type | Description |
|---|---|---|
value | str | float | None |
Returns str
def literal(value: str | float | None) -> str:
"""``value`` as a Python literal: strings in double quotes, ``float("nan")``
and ``float("inf")`` for the floats without one, and ``-0.0`` kept."""
if isinstance(value, str):
return _string(value)
if isinstance(value, float):
if math.isnan(value):
return 'float("nan")'
if math.isinf(value):
return 'float("inf")' if value > 0 else '-float("inf")'
return repr(value)import_named#
import_named(module, name, *, type_only=False) -> BindingA named import (from module import name) any module can use.
| Parameter | Type | Description |
|---|---|---|
module | str | |
name | str | |
type_only | bool = False |
Returns Binding
def import_named(module: str, name: str, *, type_only: bool = False) -> Binding:
"""A named import (``from module import name``) any module can use."""
return ImportBinding(NamedImport(module, name, name, type_only))import_namespace#
import_namespace(module, local, *, type_only=False) -> BindingA namespace import (import module as local) any module can use.
| Parameter | Type | Description |
|---|---|---|
module | str | |
local | str | |
type_only | bool = False |
Returns Binding
def import_namespace(module: str, local: str, *, type_only: bool = False) -> Binding:
"""A namespace import (``import module as local``) any module can use."""
return ImportBinding(NamespaceImport(module, local, type_only))