PYPI PACKAGE AUDIT v0.1.0 Verbesserungsbedarf

syntax-import

Führen Sie Python-Dateien aus, die um eine einzelne „Syntax-Import“-Direktive der obersten Ebene erweitert wurden, die den Quelltext und AST neu schreibt, wobei Tracebacks auf die Originalzeilen zurückgeführt werden.

PyPkgScore syntax-import
Methodik & Kriterien ♥ Donate
525 / 1000
Schnellinstallation
pip install syntax-import
1. Governance
50/200
2. PEP-Metadaten
200/200
3. Sicherheit
150/200
4. Doku & SEO
60/200
5. CI-Engineering
65/200
📣 Prüfung teilen: Teilen Sie diesen Bericht und die Vorschau in der aktuellen Sprache
Advertisement
PYPI-TELEMETRIE

Downloads & Community-Verbreitung

Letzte 30 Tage (ohne Spiegelserver)
Letzte 7 Tage
121
Letzte 30 Tage
121
Gesamt (180 Tage)
121
Metrik / Ökosystem Status / Wert Quelle
Downloads (30d / 180d) — PyPI Stats (without mirrors)
Trusted Publishing (PEP 740) ✕ Not detected PyPI Integrity / Sigstore
Django Packages — djangopackages.org
PyTech / PyPkgScore 525 / 1000 PyPkgScore Engine

Gesundheits- & Engineering-Analyse (5 Säulen)

1. Governance & Community50 / 200 ▾
LICENSE✓ 50 pts
SECURITY.md✕ 0 pts
CONTRIBUTING.md✕ 0 pts
CODE_OF_CONDUCT.md✕ 0 pts
2. PEP-Metadaten & Paketierung200 / 200 ▾
Wheel (.whl)✓ 50 pts
pyproject.toml✓ 50 pts
Project URLs✓ 50 pts
Trove Classifiers✓ 50 pts
3. Sicherheit & Lieferkette150 / 200 ▾
Null CVEs (OSV)✓ 60 pts
Trusted Publishing (OIDC)✕ 0 pts
Snyk / Audit Link✓ 40 pts
HTTPS-Repository✓ 50 pts
4. Dokumentation, SEO & Ökosystem60 / 200 ▾
Strukturierte README✓ 60 pts
Read the Docs✕ 0 pts
Django Packages✕ 0 pts
Webseite / Fachartikel✕ 0 pts
5. Engineering, CI & Qualität65 / 200 ▾
Automatisierte Tests✓ 65 pts
GitHub Actions CI✕ 0 pts
CHANGELOG.md✕ 0 pts
Env & Lockfile (uv/rye/poetry/pdm/hatch)✕ 0 pts
Advertisement
README & DOCS

Offizielle Dokumentation & Nutzungsleitfaden — syntax-import

PyPI Metadata v0.1.0
Vollständige Originaldokumentation anzeigen (Englisches 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 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