Skip to main content

syntax-import

Run "extended Python" files: the body is ordinary Python, but the file may start with one syntax import package.module directive naming a syntax module that rewrites the source text and the AST before compilation. Tracebacks and syntax errors point at the lines of the original file. Pure standard library, Python 3.9+.

#!/usr/bin/env python3
"""Optional module docstring."""
# comments are fine
syntax import syntax_import.examples.combo
from __future__ import annotations

items = [3, 1, 2]
unless items |> len:
    print("empty list")
pip install syntax-import
syntax-import script.spy arg1 arg2          # or: python -m syntax_import script.spy arg1 arg2

1. Directive rules

Rule On violation
Form: syntax import package.module (trailing comment and backslash continuation allowed) DirectiveError
Must be the first statement: only blank lines, comments (incl. shebang and encoding cookie) and at most one module docstring may precede it; it must not be indented DirectiveError
Must come before every from __future__ import DirectiveError
At most one per file, naming exactly one module (syntax import a, b is rejected) DirectiveError
Files without a directive run as plain Python

DirectiveError is a subclass of SyntaxError and carries the correct file name, line number and offending line. The text syntax import inside string literals is never mistaken for a directive.

How the directive line is removed: it is blanked. The physical line(s) of the directive are replaced by empty lines (only the line ending is kept), so the text handed to the editor has the same number of lines as the file and line numbers match one-to-one without any extra mapping. Module docstrings and from __future__ imports stay valid.

2. The syntax module contract

A syntax module is an ordinary module (pure Python or a C extension) and can be imported normally. To be used with syntax import it must export:

def text_editor(text: str, original_text: str, context: dict) -> tuple[str, LineMapLike]: ...
def ast_editor(tree: ast.Module, line_map: LineMap, context: dict) -> ast.Module | None: ...

If either is missing (or not callable), SyntaxModuleError (a subclass of ImportError) is raised.

text_editor(text, original_text, context)

  • text: the code to rewrite (directive line already blanked).
  • original_text: the original code. At top level text == original_text and context == {}; when called by a composite module, text is the output of the previous step and context carries delegation information (see section 4).
  • Returns (new_text, line_map). line_map maps lines of new_text -> lines of the received text and may be:
    • None: identity (line structure unchanged);
    • a dict {new_lineno: old_lineno or None}; None / unlisted lines are synthesized lines;
    • a list/tuple: seq[i] is the old line of new line i + 1;
    • a LineMap.
  • May raise SyntaxError with line numbers of the received text; the framework fills in the file name and converts the line numbers.

ast_editor(tree, line_map, context)

  • tree: result of ast.parse(new_text); node positions refer to new_text.
  • line_map: a LineMap mapping tree lines -> original lines (file lines at top level).
  • context: the same dict the text_editor received, so information can flow between stages.
  • Returns a new ast.Module, or None for in-place edits. An editor that only accepts (tree, line_map) is supported too; for callables without an inspectable signature (typical of C functions) three arguments are tried first, then two on an argument-count TypeError.
  • Synthesized nodes need no positions: the framework calls fix_missing_locations and then remaps.

LineMap

LineMap.get(n) is an exact lookup; LineMap.resolve(n) falls back to the nearest preceding mapped line (so synthesized lines point at the line that produced them); a.compose(b) composes maps (C->B with B->A gives C->A).

3. Pipeline and tracebacks

read source (honouring the encoding cookie) -> validate and blank the directive -> import syntax module
-> text_editor(text, text, {}) -> ast.parse(new_text) -> ast_editor(tree, line_map, context)
-> fix_missing_locations -> remap node lines to the original file -> compile -> exec in a fresh module

The show option controls what tracebacks display:

  • show="original" (default): every AST node is remapped to original file lines, so tracebacks show the code of the real file. When a line was changed by the transformation, column offsets are widened to the whole line so carets never point at the wrong place. SyntaxErrors from ast.parse, from the ast_editor and from compile are remapped as well, with a note "transformed code line N: ...".
  • show="modified": line numbers of the modified code are kept and the modified code is registered in linecache under the pseudo file name "<file> <syntax import module>", so tracebacks show the modified code. CLI flag: --show-modified.

4. Delegation: combining several syntaxes

A file can only have one syntax import. To combine syntaxes, write a new composite syntax module that delegates:

# mysyntax.py
from syntax_import import delegate_text, delegate_ast
from syntax_import.examples import pipe, unless

MODULES = [pipe, unless]          # the order is part of conflict resolution

def text_editor(text, original_text, context):
    return delegate_text(MODULES, text, original_text, context)

def ast_editor(tree, line_map, context):
    return delegate_ast(MODULES, tree, line_map, context)

# or in one line: text_editor, ast_editor = make_composite(pipe, unless)

delegate_text calls each sub-module's text_editor in turn: each receives the previous output, the same original_text and a fresh sub-context; the line maps of all steps are composed automatically and the result follows the text_editor contract. A SyntaxError raised by a sub-module is converted to line numbers of the composite's input. delegate_ast calls the ast_editors in turn (reverse=True for reverse order), giving each sub-module back the context it used in the text stage. Delegation can be nested.

Context received by a sub-module:

Key Meaning
delegator name of the delegating composite module
delegation_chain delegators from the outermost one down to the current composite
index / modules index of the current sub-module / names of all sub-modules
line_map LineMap: text received by this sub-module -> original_text
previous_steps DelegationSteps of earlier steps (input, output, maps)
parent_context the context the composite itself received
shared a dict shared across all levels, for negotiation between modules
stage "text" or "ast"

Resolving conflicts

  • Ordering: in examples/combo.py, unless needs the colon on the same logical line while pipe allows |> continuation lines, so pipe must run before unless (the other order fails with "missing a colon").
  • Hooks: delegate_text(..., before=f, after=g)
    • before(index, module, text, sub_context): rewrite a sub-module's input before it runs;
    • after(step): inspect / rewrite its output afterwards (step is a DelegationStep);
    • return None (unchanged), a str (same line structure) or (str, line_map) (new text -> text received by the hook).
    • delegate_ast(..., before=, after=) hooks take (index, module, tree, sub_context) and return a new tree or None.
  • Full control: a composite module is itself an ordinary syntax module and may do anything before or after delegating.

5. Usage

Command line:

syntax-import file.spy [args...]          # sys.argv = ['file.spy', args...], __name__ == '__main__'
syntax-import --show-modified file.spy
syntax-import --dump file.spy             # print transformed code with "new line -> original line"; do not run
syntax-import --ext .xpy file.xpy         # extension recognized by the import hook (default .spy)
syntax-import --no-color file.spy         # disable color in tracebacks

The CLI adds the script's directory to sys.path and installs the import hook, so a script can import neighbouring .spy modules.

API:

import syntax_import as si

si.run_file("a.spy", argv=["a.spy", "x"])        # returns the module namespace dict
si.run_source(code_str, "<snippet>")             # source string (registered in linecache)
code = si.compile_source(code_str, "a.spy")      # just the code object
res = si.transform(code_str, "a.spy", show="modified")  # new_text / line_map / tree / code
si.install_import_hook((".spy",))                # afterwards `import xxx` loads xxx.spy or xxx/__init__.spy
si.get_current_source()                          # inside an editor: current file and syntax module name

The import hook follows sys.path order; a regular .py module or package of the same name in the same directory takes precedence.

6. Examples (syntax_import/examples/, installed with the package)

File Description
unless.py text level: unless cond: -> if not (cond):, identity line map
pipe.py text + AST level: x |> f -> f(x), x |> f(a, _) -> f(a, x); |> continuation lines (fewer lines, non-identity line map); uses the context to pass its marker between stages
combo.py composite module delegating to pipe and unless; shows an ordering conflict and an after hook
*.spy scripts: hello_unless, hello_pipe, hello_combo, error_demo (traceback line mapping), use_import_hook + mathutils
EX=$(python -c "import os, syntax_import.examples as e; print(os.path.dirname(e.__file__))")
syntax-import "$EX/hello_combo.spy"
syntax-import "$EX/error_demo.spy"     # traceback points at lines 13 and 5 of the original file

7. Tests

From a source checkout:

pip install .
python -m unittest discover -s tests -t .

8. Limitations

  • Before calling text_editor the framework scans for the directive with tokenize; if the custom syntax makes tokenize fail, the rest of the file is scanned line by line with a regex.
  • In "original" mode, positions inside rewritten lines are only accurate to the line; the columns cover the whole line.

License

MIT

Metadata

Release files for syntax-import 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for syntax-import 0.1.0
File Size Uploaded Provenance Actions
syntax_import-0.1.0.tar.gz 23.6 kB Without provenance Details for syntax_import-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for syntax-import 0.1.0
File Interpreter ABI Platform Actions
syntax_import-0.1.0-py3-none-any.whl Python 3 none any Details for syntax_import-0.1.0-py3-none-any.whl

Total release size: 30.1 kB

Release files / syntax_import-0.1.0.tar.gz

Download URL syntax_import-0.1.0.tar.gz
Size 23.6 kB
Tags Source
SHA-256 checksum
How to use checksums
50a3b088ffa1e59d412de2f697247b1133f0738ffc20275da877d3e3d554ce42
BLAKE2b-256 checksum
How to use checksums
3924c5bf5cd3f90a01c8503edeed88da0b3b17deadae97666cbb94257c292b15
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.8

Release files / syntax_import-0.1.0-py3-none-any.whl

Download URL syntax_import-0.1.0-py3-none-any.whl
Size 6.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
89c2b9046fb6561c6b1ac5c82ef785cdf37f95d59738f9dd344953a56b7467d8
BLAKE2b-256 checksum
How to use checksums
1f26cf4e1ca1939e4d28d0ca0f29f55c0f51c7a982ef74788aee7dd408c56c3c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.8

Security for syntax-import 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page