syntax-import
Run Python files extended by a single top-level `syntax import` directive that rewrites the source text and AST, with tracebacks mapped back to the original lines.
Downloads & Community Adoption
Health & Engineering Analysis (5 Pillars)
1. Governance & Community50 / 200 ▾
2. PEP Metadata & Packaging200 / 200 ▾
3. Security & Supply Chain150 / 200 ▾
4. Documentation, SEO & Ecosystem60 / 200 ▾
5. Engineering, CI & Quality65 / 200 ▾
Official Documentation & Usage Guide — syntax-import
Show full original documentation (English README) ▾
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 leveltext == original_textandcontext == {}; when called by a composite module,textis the output of the previous step andcontextcarries delegation information (see section 4).- Returns
(new_text, line_map).line_mapmaps lines of new_text -> lines of the receivedtextand 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 linei + 1; - a
LineMap.
- May raise
SyntaxErrorwith line numbers of the receivedtext; the framework fills in the file name and converts the line numbers.
ast_editor(tree, line_map, context)
tree: result ofast.parse(new_text); node positions refer to new_text.line_map: aLineMapmapping tree lines -> original lines (file lines at top level).context: the same dict thetext_editorreceived, so information can flow between stages.- Returns a new
ast.Module, orNonefor 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-countTypeError. - Synthesized nodes need no positions: the framework calls
fix_missing_locationsand 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 fromast.parse, from theast_editorand fromcompileare 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 inlinecacheunder 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,unlessneeds the colon on the same logical line whilepipeallows|>continuation lines, sopipemust run beforeunless(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 (stepis aDelegationStep);- return
None(unchanged), astr(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_editorthe framework scans for the directive withtokenize; if the custom syntax makestokenizefail, 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