Skip to content

Synt¤

Write Python with Python. Inspired by jennifer.

Python-3.12 GitHub top language GitHub Actions Workflow Status Codecov PyPI - Downloads PyPI - License PyPI - Version

Synt is a library for developers to write elegant machine-generated Python code.

Documentation


Installation¤

To install Synt, use your preferred package manager and add synt to your dependencies, e.g. by pip:

pip install synt

Then, import Synt:

import synt                    # directly import Synt, or
from synt.prelude import *     # import pre-organized utilities from `prelude`.

Overview¤

Synt creates a Python-based DSL for writing actual Python code.

Different from text-based template systems like Jinja, Synt allows you to construct Python code generator as-is:

1
2
3
4
5
6
7
8
from synt.prelude import *

expression = id_("foo") \
    .expr() \
    .attr("bar") \
    .call(buzz=id_("buzz"))

assert expression.into_code() == "foo.bar(buzz=buzz)"

Usage¤

Synt keeps most of Python's standard operations as-is. Currently, Synt only supports generating expressions, and statement generating is on the to-do list.

Typically, special syntax in Python can be used with alias methods with the same name. For example, the following example shows how to create a generator comprehension:

from synt.prelude import *

comp = fstring("Item: ", fnode(id_("x"))) \
    .for_(id_("x")) \
    .in_(id_("it"))

# note: Comprehension expressions are a bit different
#       because it accepts any amount of `for`s and `if`s.
#       Thus we must add a `.expr()` to force it to be an expression.
assert comp.expr().into_code() == r'(f"Item: {x}" for x in it)'

For full api documentation, see the Documentation page.