Skip to content

synt ¤

code ¤

IntoCode ¤

Source code in synt/code.py
class IntoCode(metaclass=ABCMeta):
    @abstractmethod
    def into_code(self) -> str:
        """Converts the object into a string of Python code."""

into_code abstractmethod ¤

into_code() -> str

Converts the object into a string of Python code.

Source code in synt/code.py
@abstractmethod
def into_code(self) -> str:
    """Converts the object into a string of Python code."""

expr ¤

alias ¤

Alias ¤

Bases: Expression

Import alias.

Examples:

1
2
3
4
al = id_("a").as_("b")
assert al.into_code() == "a as b"
p = path(id_('foo'), id_('bar')).as_(id_("baz"))
assert p.into_code() == "foo.bar as baz"
References

alias.

Source code in synt/expr/alias.py
class Alias(Expression):
    r"""Import alias.

    Examples:
        ```python
        al = id_("a").as_("b")
        assert al.into_code() == "a as b"
        p = path(id_('foo'), id_('bar')).as_(id_("baz"))
        assert p.into_code() == "foo.bar as baz"
        ```

    References:
        [`alias`](https://docs.python.org/3/library/ast.html#ast.alias).
    """

    names: ModPath | Expression
    """The names of the alias item."""
    asname: Identifier
    """The alias name."""

    expr_type = ExprType.Atom
    precedence = ExprPrecedence.Atom

    def __init__(self, names: Identifier | ModPath | Expression, asname: Identifier):
        """Initialize a new alias.

        Args:
            names: The names of the alias item.
            asname: The alias name.
        """
        if isinstance(names, Identifier):
            self.names = ModPath(names)
        else:
            self.names = names
        self.asname = asname

    def into_code(self) -> str:
        return f"{self.names.into_code()} as {self.asname.into_code()}"
names instance-attribute ¤

The names of the alias item.

expr_type class-attribute instance-attribute ¤
expr_type = Atom
precedence class-attribute instance-attribute ¤
precedence = Atom
asname instance-attribute ¤
asname: Identifier = asname

The alias name.

__init__ ¤
1
2
3
4
__init__(
    names: Identifier | ModPath | Expression,
    asname: Identifier,
)

Initialize a new alias.

Parameters:

Name Type Description Default
names Identifier | ModPath | Expression

The names of the alias item.

required
asname Identifier

The alias name.

required
Source code in synt/expr/alias.py
def __init__(self, names: Identifier | ModPath | Expression, asname: Identifier):
    """Initialize a new alias.

    Args:
        names: The names of the alias item.
        asname: The alias name.
    """
    if isinstance(names, Identifier):
        self.names = ModPath(names)
    else:
        self.names = names
    self.asname = asname
into_code ¤
into_code() -> str
Source code in synt/expr/alias.py
def into_code(self) -> str:
    return f"{self.names.into_code()} as {self.asname.into_code()}"

attribute ¤

Attribute ¤

Bases: Expression

The operation to get a value's attribute.

References

Attribute.

Source code in synt/expr/attribute.py
class Attribute(expr.Expression):
    r"""The operation to get a value's attribute.

    References:
        [Attribute](https://docs.python.org/3/library/ast.html#ast.Attribute).
    """

    target: expr.Expression
    """The target of the operation."""
    attribute_name: str
    """The attribute's name."""

    precedence = expr.ExprPrecedence.Call
    expr_type = expr.ExprType.Attribute

    def __init__(self, target: expr.IntoExpression, attr: str):
        """Initialize an attribute expression.

        Args:
            target: The target of the operation.
            attr: The attribute's name.
        """
        self.target = target.into_expression()
        self.attribute_name = attr

        if self.target.precedence > self.precedence:
            self.target = self.target.wrapped()

    def into_code(self) -> str:
        return f"{self.target.into_code()}.{self.attribute_name}"
precedence class-attribute instance-attribute ¤
precedence = Call
expr_type class-attribute instance-attribute ¤
expr_type = Attribute
target instance-attribute ¤
target: Expression = into_expression()

The target of the operation.

attribute_name instance-attribute ¤
attribute_name: str = attr

The attribute's name.

__init__ ¤
__init__(target: IntoExpression, attr: str)

Initialize an attribute expression.

Parameters:

Name Type Description Default
target IntoExpression

The target of the operation.

required
attr str

The attribute's name.

required
Source code in synt/expr/attribute.py
def __init__(self, target: expr.IntoExpression, attr: str):
    """Initialize an attribute expression.

    Args:
        target: The target of the operation.
        attr: The attribute's name.
    """
    self.target = target.into_expression()
    self.attribute_name = attr

    if self.target.precedence > self.precedence:
        self.target = self.target.wrapped()
into_code ¤
into_code() -> str
Source code in synt/expr/attribute.py
def into_code(self) -> str:
    return f"{self.target.into_code()}.{self.attribute_name}"

binary_op ¤

BinaryOpType ¤

Bases: IntEnum

Binary operator type.

Exception: Although NamedExpr takes the form of a binary operator, it is not a binary operator (at least not in synt).

References

expr.ExprPrecedence

Source code in synt/expr/binary_op.py
class BinaryOpType(IntEnum):
    r"""Binary operator type.

    **Exception:**
    Although [`NamedExpr`][synt.expr.expr.ExprPrecedence.NamedExpr]
    takes the form of a binary operator, it is not a binary operator (at least not in `synt`).

    References:
        [`expr.ExprPrecedence`][synt.expr.expr.ExprPrecedence]
    """

    Add = 0
    """Addition operator `+`."""
    Sub = 1
    """Subtraction operator `-`."""
    Mul = 2
    """Multiplication operator `*`."""
    Div = 3
    """Division operator `/`."""
    FloorDiv = 4
    """Floor division operator `//`."""
    Mod = 5
    """Modulus(remainder) operator `%`."""
    Pow = 6
    """Exponent(power) operator `**`."""
    At = 7
    """At(matrix multiplication) operator `@`."""
    LShift = 8
    """Left shift operator `<<`."""
    RShift = 9
    """Right shift operator `>>`."""
    In = 10
    """Membership test operator `in`."""
    NotIn = 11
    """Negative membership test operator group `not in`."""
    Is = 12
    """Identity test operator `is`."""
    IsNot = 13
    """Negative identity test operator group `is not`."""
    Less = 14
    """'Less than' operator `<`."""
    LessEqual = 15
    """'Less than or Equal' operator `<=`."""
    Greater = 16
    """'Greater than' operator `>`."""
    GreaterEqual = 17
    """'Greater than or Equal' operator `>=`."""
    Equal = 18
    """'Equal' operator `==`."""
    NotEqual = 19
    """Negative 'Equal' operator `!=`."""
    BitAnd = 20
    """Bitwise AND operator `&`."""
    BitOr = 21
    """Bitwise OR operator `|`."""
    BitXor = 22
    """Bitwise XOR operator `^`."""
    BoolAnd = 23
    """Boolean AND operator `and`."""
    BoolOr = 24
    """Boolean OR operator `or`."""

    def to_precedence(self) -> expr.ExprPrecedence:
        """Get the operator's backend expression's precedence."""
        match self:
            case BinaryOpType.Add | BinaryOpType.Sub:
                return expr.ExprPrecedence.Additive
            case (
                BinaryOpType.Mul
                | BinaryOpType.Div
                | BinaryOpType.FloorDiv
                | BinaryOpType.Mod
                | BinaryOpType.At
            ):
                return expr.ExprPrecedence.Multiplicative
            case BinaryOpType.Pow:
                return expr.ExprPrecedence.Exponential
            case BinaryOpType.LShift | BinaryOpType.RShift:
                return expr.ExprPrecedence.Shift
            case (
                BinaryOpType.In
                | BinaryOpType.NotIn
                | BinaryOpType.Is
                | BinaryOpType.IsNot
                | BinaryOpType.Less
                | BinaryOpType.LessEqual
                | BinaryOpType.Greater
                | BinaryOpType.GreaterEqual
                | BinaryOpType.Equal
                | BinaryOpType.NotEqual
            ):
                return expr.ExprPrecedence.Comparative
            case BinaryOpType.BitAnd:
                return expr.ExprPrecedence.BitAnd
            case BinaryOpType.BitOr:
                return expr.ExprPrecedence.BitOr
            case BinaryOpType.BitXor:
                return expr.ExprPrecedence.BitXor
            case BinaryOpType.BoolAnd:
                return expr.ExprPrecedence.BoolAnd
            case BinaryOpType.BoolOr:
                return expr.ExprPrecedence.BoolOr
            case _:
                raise ValueError(
                    f"Unrecognized binary operator type: {self} [{self.value}]"
                )

    def into_code(self) -> str:
        """
        Raises:
            ValueError: If the provided operator type is not recognized.
        """
        match self:
            case BinaryOpType.Add:
                return "+"
            case BinaryOpType.Sub:
                return "-"
            case BinaryOpType.Mul:
                return "*"
            case BinaryOpType.Div:
                return "/"
            case BinaryOpType.FloorDiv:
                return "//"
            case BinaryOpType.Mod:
                return "%"
            case BinaryOpType.Pow:
                return "**"
            case BinaryOpType.At:
                return "@"
            case BinaryOpType.LShift:
                return "<<"
            case BinaryOpType.RShift:
                return ">>"
            case BinaryOpType.In:
                return "in"
            case BinaryOpType.NotIn:
                return "not in"
            case BinaryOpType.Is:
                return "is"
            case BinaryOpType.IsNot:
                return "is not"
            case BinaryOpType.Less:
                return "<"
            case BinaryOpType.LessEqual:
                return "<="
            case BinaryOpType.Greater:
                return ">"
            case BinaryOpType.GreaterEqual:
                return ">="
            case BinaryOpType.Equal:
                return "=="
            case BinaryOpType.NotEqual:
                return "!="
            case BinaryOpType.BitAnd:
                return "&"
            case BinaryOpType.BitOr:
                return "|"
            case BinaryOpType.BitXor:
                return "^"
            case BinaryOpType.BoolAnd:
                return "and"
            case BinaryOpType.BoolOr:
                return "or"
            case _:
                raise ValueError(f"Unrecognized binary operator type: {self}")
Add class-attribute instance-attribute ¤
Add = 0

Addition operator +.

Sub class-attribute instance-attribute ¤
Sub = 1

Subtraction operator -.

Mul class-attribute instance-attribute ¤
Mul = 2

Multiplication operator *.

Div class-attribute instance-attribute ¤
Div = 3

Division operator /.

FloorDiv class-attribute instance-attribute ¤
FloorDiv = 4

Floor division operator //.

Mod class-attribute instance-attribute ¤
Mod = 5

Modulus(remainder) operator %.

Pow class-attribute instance-attribute ¤
Pow = 6

Exponent(power) operator **.

At class-attribute instance-attribute ¤
At = 7

At(matrix multiplication) operator @.

LShift class-attribute instance-attribute ¤
LShift = 8

Left shift operator <<.

RShift class-attribute instance-attribute ¤
RShift = 9

Right shift operator >>.

In class-attribute instance-attribute ¤
In = 10

Membership test operator in.

NotIn class-attribute instance-attribute ¤
NotIn = 11

Negative membership test operator group not in.

Is class-attribute instance-attribute ¤
Is = 12

Identity test operator is.

IsNot class-attribute instance-attribute ¤
IsNot = 13

Negative identity test operator group is not.

Less class-attribute instance-attribute ¤
Less = 14

'Less than' operator <.

LessEqual class-attribute instance-attribute ¤
LessEqual = 15

'Less than or Equal' operator <=.

Greater class-attribute instance-attribute ¤
Greater = 16

'Greater than' operator >.

GreaterEqual class-attribute instance-attribute ¤
GreaterEqual = 17

'Greater than or Equal' operator >=.

Equal class-attribute instance-attribute ¤
Equal = 18

'Equal' operator ==.

NotEqual class-attribute instance-attribute ¤
NotEqual = 19

Negative 'Equal' operator !=.

BitAnd class-attribute instance-attribute ¤
BitAnd = 20

Bitwise AND operator &.

BitOr class-attribute instance-attribute ¤
BitOr = 21

Bitwise OR operator |.

BitXor class-attribute instance-attribute ¤
BitXor = 22

Bitwise XOR operator ^.

BoolAnd class-attribute instance-attribute ¤
BoolAnd = 23

Boolean AND operator and.

BoolOr class-attribute instance-attribute ¤
BoolOr = 24

Boolean OR operator or.

to_precedence ¤
to_precedence() -> ExprPrecedence

Get the operator's backend expression's precedence.

Source code in synt/expr/binary_op.py
def to_precedence(self) -> expr.ExprPrecedence:
    """Get the operator's backend expression's precedence."""
    match self:
        case BinaryOpType.Add | BinaryOpType.Sub:
            return expr.ExprPrecedence.Additive
        case (
            BinaryOpType.Mul
            | BinaryOpType.Div
            | BinaryOpType.FloorDiv
            | BinaryOpType.Mod
            | BinaryOpType.At
        ):
            return expr.ExprPrecedence.Multiplicative
        case BinaryOpType.Pow:
            return expr.ExprPrecedence.Exponential
        case BinaryOpType.LShift | BinaryOpType.RShift:
            return expr.ExprPrecedence.Shift
        case (
            BinaryOpType.In
            | BinaryOpType.NotIn
            | BinaryOpType.Is
            | BinaryOpType.IsNot
            | BinaryOpType.Less
            | BinaryOpType.LessEqual
            | BinaryOpType.Greater
            | BinaryOpType.GreaterEqual
            | BinaryOpType.Equal
            | BinaryOpType.NotEqual
        ):
            return expr.ExprPrecedence.Comparative
        case BinaryOpType.BitAnd:
            return expr.ExprPrecedence.BitAnd
        case BinaryOpType.BitOr:
            return expr.ExprPrecedence.BitOr
        case BinaryOpType.BitXor:
            return expr.ExprPrecedence.BitXor
        case BinaryOpType.BoolAnd:
            return expr.ExprPrecedence.BoolAnd
        case BinaryOpType.BoolOr:
            return expr.ExprPrecedence.BoolOr
        case _:
            raise ValueError(
                f"Unrecognized binary operator type: {self} [{self.value}]"
            )
into_code ¤
into_code() -> str

Raises:

Type Description
ValueError

If the provided operator type is not recognized.

Source code in synt/expr/binary_op.py
def into_code(self) -> str:
    """
    Raises:
        ValueError: If the provided operator type is not recognized.
    """
    match self:
        case BinaryOpType.Add:
            return "+"
        case BinaryOpType.Sub:
            return "-"
        case BinaryOpType.Mul:
            return "*"
        case BinaryOpType.Div:
            return "/"
        case BinaryOpType.FloorDiv:
            return "//"
        case BinaryOpType.Mod:
            return "%"
        case BinaryOpType.Pow:
            return "**"
        case BinaryOpType.At:
            return "@"
        case BinaryOpType.LShift:
            return "<<"
        case BinaryOpType.RShift:
            return ">>"
        case BinaryOpType.In:
            return "in"
        case BinaryOpType.NotIn:
            return "not in"
        case BinaryOpType.Is:
            return "is"
        case BinaryOpType.IsNot:
            return "is not"
        case BinaryOpType.Less:
            return "<"
        case BinaryOpType.LessEqual:
            return "<="
        case BinaryOpType.Greater:
            return ">"
        case BinaryOpType.GreaterEqual:
            return ">="
        case BinaryOpType.Equal:
            return "=="
        case BinaryOpType.NotEqual:
            return "!="
        case BinaryOpType.BitAnd:
            return "&"
        case BinaryOpType.BitOr:
            return "|"
        case BinaryOpType.BitXor:
            return "^"
        case BinaryOpType.BoolAnd:
            return "and"
        case BinaryOpType.BoolOr:
            return "or"
        case _:
            raise ValueError(f"Unrecognized binary operator type: {self}")

BinaryOp ¤

Bases: Expression

Binary operation.

Source code in synt/expr/binary_op.py
class BinaryOp(expr.Expression):
    r"""Binary operation."""

    left: expr.Expression
    """Left operand expression."""
    right: expr.Expression
    """Right operand expression."""
    op_type: BinaryOpType
    """Operator type."""

    expr_type = expr.ExprType.BinaryOp

    def __init__(
        self, op: BinaryOpType, left: expr.IntoExpression, right: expr.IntoExpression
    ):
        """Initialize a binary operation.

        Args:
            op: Binary operator type.
            left: Left operand.
            right: Right operand.
        """
        self.left = left.into_expression()
        self.right = right.into_expression()
        self.op_type = op

        if self.left.precedence > self.precedence:
            self.left = self.left.wrapped()
        if self.right.precedence > self.precedence:
            self.right = self.right.wrapped()

    def into_code(self) -> str:
        return f"{self.left.into_code()} {self.op_type.into_code()} {self.right.into_code()}"

    @property
    def precedence(self) -> ExprPrecedence:
        """expr.Expression precedence.

        References:
            [BinaryOpType.to_precedence][synt.expr.binary_op.BinaryOpType.to_precedence].
        """
        return self.op_type.to_precedence()
expr_type class-attribute instance-attribute ¤
expr_type = BinaryOp
left instance-attribute ¤
left: Expression = into_expression()

Left operand expression.

right instance-attribute ¤
right: Expression = into_expression()

Right operand expression.

op_type instance-attribute ¤
op_type: BinaryOpType = op

Operator type.

precedence property ¤
precedence: ExprPrecedence

expr.Expression precedence.

References

BinaryOpType.to_precedence.

__init__ ¤
1
2
3
4
5
__init__(
    op: BinaryOpType,
    left: IntoExpression,
    right: IntoExpression,
)

Initialize a binary operation.

Parameters:

Name Type Description Default
op BinaryOpType

Binary operator type.

required
left IntoExpression

Left operand.

required
right IntoExpression

Right operand.

required
Source code in synt/expr/binary_op.py
def __init__(
    self, op: BinaryOpType, left: expr.IntoExpression, right: expr.IntoExpression
):
    """Initialize a binary operation.

    Args:
        op: Binary operator type.
        left: Left operand.
        right: Right operand.
    """
    self.left = left.into_expression()
    self.right = right.into_expression()
    self.op_type = op

    if self.left.precedence > self.precedence:
        self.left = self.left.wrapped()
    if self.right.precedence > self.precedence:
        self.right = self.right.wrapped()
into_code ¤
into_code() -> str
Source code in synt/expr/binary_op.py
def into_code(self) -> str:
    return f"{self.left.into_code()} {self.op_type.into_code()} {self.right.into_code()}"

call ¤

Call ¤

Bases: Expression

Calling a value.

References

Call.

Source code in synt/expr/call.py
class Call(expr.Expression):
    r"""Calling a value.

    References:
        [Call](https://docs.python.org/3/library/ast.html#ast.Call).
    """

    target: expr.Expression
    """Call target."""
    args: list[expr.Expression]
    """Positional arguments of the call."""
    keywords: list[Keyword]
    """Keyword arguments of the call."""

    precedence = expr.ExprPrecedence.Call
    expr_type = expr.ExprType.Call

    def __init__(
        self,
        target: expr.IntoExpression,
        args: list[expr.IntoExpression],
        keywords: list[Keyword],
    ):
        """Initialize a new `Call`.

        Args:
            target: Call target.
            args: Positional arguments of the call.
            keywords: Keyword arguments of the call.
        """
        self.target = target.into_expression()
        if self.target.precedence > self.precedence:
            self.target = self.target.wrapped()

        self.args = [arg.into_expression() for arg in args]
        self.keywords = keywords

    def into_code(self) -> str:
        arg_text = ""
        if self.args:
            args_text = ", ".join(arg.into_code() for arg in self.args)
            if self.keywords:
                kwargs_text = ", ".join(kw.into_code() for kw in self.keywords)
                arg_text = f"{args_text}, {kwargs_text}"
            else:
                arg_text = args_text
        elif self.keywords:
            arg_text = ", ".join(kw.into_code() for kw in self.keywords)

        return f"{self.target.into_code()}({arg_text})"
precedence class-attribute instance-attribute ¤
precedence = Call
expr_type class-attribute instance-attribute ¤
expr_type = Call
target instance-attribute ¤
target: Expression = into_expression()

Call target.

args instance-attribute ¤
args: list[Expression] = [into_expression() for arg in args]

Positional arguments of the call.

keywords instance-attribute ¤
keywords: list[Keyword] = keywords

Keyword arguments of the call.

__init__ ¤
1
2
3
4
5
__init__(
    target: IntoExpression,
    args: list[IntoExpression],
    keywords: list[Keyword],
)

Initialize a new Call.

Parameters:

Name Type Description Default
target IntoExpression

Call target.

required
args list[IntoExpression]

Positional arguments of the call.

required
keywords list[Keyword]

Keyword arguments of the call.

required
Source code in synt/expr/call.py
def __init__(
    self,
    target: expr.IntoExpression,
    args: list[expr.IntoExpression],
    keywords: list[Keyword],
):
    """Initialize a new `Call`.

    Args:
        target: Call target.
        args: Positional arguments of the call.
        keywords: Keyword arguments of the call.
    """
    self.target = target.into_expression()
    if self.target.precedence > self.precedence:
        self.target = self.target.wrapped()

    self.args = [arg.into_expression() for arg in args]
    self.keywords = keywords
into_code ¤
into_code() -> str
Source code in synt/expr/call.py
def into_code(self) -> str:
    arg_text = ""
    if self.args:
        args_text = ", ".join(arg.into_code() for arg in self.args)
        if self.keywords:
            kwargs_text = ", ".join(kw.into_code() for kw in self.keywords)
            arg_text = f"{args_text}, {kwargs_text}"
        else:
            arg_text = args_text
    elif self.keywords:
        arg_text = ", ".join(kw.into_code() for kw in self.keywords)

    return f"{self.target.into_code()}({arg_text})"

Keyword ¤

Bases: IntoCode

Keyword arguments of a object call.

References

Call Keyword(PythonAst)

Source code in synt/expr/call.py
class Keyword(code.IntoCode):
    r"""Keyword arguments of a object call.

    References:
        [`Call`][synt.expr.call.Call]
        [`Keyword`(PythonAst)](https://docs.python.org/3/library/ast.html#ast.keyword)
    """

    key: Identifier
    """Keyword."""
    value: expr.Expression
    """Value for the argument."""

    def __init__(self, key: Identifier, value: expr.IntoExpression):
        """Initialize a new keyword argument.

        Args:
            key: Keyword.
            value: Value for the argument.
        """
        self.key = key
        self.value = value.into_expression()

    def into_code(self) -> str:
        return f"{self.key.into_code()}={self.value.into_code()}"
key instance-attribute ¤

Keyword.

value instance-attribute ¤
value: Expression = into_expression()

Value for the argument.

__init__ ¤
__init__(key: Identifier, value: IntoExpression)

Initialize a new keyword argument.

Parameters:

Name Type Description Default
key Identifier

Keyword.

required
value IntoExpression

Value for the argument.

required
Source code in synt/expr/call.py
def __init__(self, key: Identifier, value: expr.IntoExpression):
    """Initialize a new keyword argument.

    Args:
        key: Keyword.
        value: Value for the argument.
    """
    self.key = key
    self.value = value.into_expression()
into_code ¤
into_code() -> str
Source code in synt/expr/call.py
def into_code(self) -> str:
    return f"{self.key.into_code()}={self.value.into_code()}"

closure ¤

lambda_ module-attribute ¤

lambda_ = ClosureBuilder

Closure ¤

Bases: Expression, IntoCode

Python's closure expression, aka lambda.

Notes

In Python, a lambda expression can have a single expression as its body. Synt won't try to create a separate function containing multiple statements, you must do it yourself.

References

expr.ExprPrecedence.Lambda.

Source code in synt/expr/closure.py
class Closure(expr.Expression, code.IntoCode):
    r"""Python's closure expression, aka `lambda`.

    Notes:
        In Python, a lambda expression can have a single expression as its body.
        Synt won't try to create a separate function containing multiple statements,
        you must do it yourself.

    References:
        [expr.ExprPrecedence.Lambda][synt.expr.expr.ExprPrecedence.Lambda].
    """

    args: list[Identifier]
    """Argument list."""
    body: expr.Expression
    """expr.Expression body."""

    precedence = expr.ExprPrecedence.Lambda
    expr_type = expr.ExprType.Closure

    def __init__(self, args: list[Identifier], body: expr.IntoExpression):
        """Initialize a closure expression.

        Args:
            args: Argument list.
            body: expr.Expression body.
        """
        self.args = args
        self.body = body.into_expression()
        if self.body.precedence > self.precedence:
            self.body = self.body.wrapped()

    def into_code(self) -> str:
        return f"lambda {', '.join(arg.into_code() for arg in self.args)}: {self.body.into_code()}"
precedence class-attribute instance-attribute ¤
precedence = Lambda
expr_type class-attribute instance-attribute ¤
expr_type = Closure
args instance-attribute ¤

Argument list.

body instance-attribute ¤
body: Expression = into_expression()

expr.Expression body.

__init__ ¤
__init__(args: list[Identifier], body: IntoExpression)

Initialize a closure expression.

Parameters:

Name Type Description Default
args list[Identifier]

Argument list.

required
body IntoExpression

expr.Expression body.

required
Source code in synt/expr/closure.py
def __init__(self, args: list[Identifier], body: expr.IntoExpression):
    """Initialize a closure expression.

    Args:
        args: Argument list.
        body: expr.Expression body.
    """
    self.args = args
    self.body = body.into_expression()
    if self.body.precedence > self.precedence:
        self.body = self.body.wrapped()
into_code ¤
into_code() -> str
Source code in synt/expr/closure.py
def into_code(self) -> str:
    return f"lambda {', '.join(arg.into_code() for arg in self.args)}: {self.body.into_code()}"

ClosureBuilder ¤

Builder for Closure.

Examples:

1
2
3
4
5
6
closure = (
    lambda_(id_("x"), id_("y")) # initial a closure builder
    .join(id_("z")) # append new argument, optional
    .return_(id_("x").expr() + id_("y") + id_("z")) # set the expression to be returned and build the closure
)
assert closure.into_code() == "lambda x, y, z: x + y + z"
Source code in synt/expr/closure.py
class ClosureBuilder:
    r"""Builder for [`Closure`][synt.expr.closure.Closure].

    Examples:
        ```python
        closure = (
            lambda_(id_("x"), id_("y")) # initial a closure builder
            .join(id_("z")) # append new argument, optional
            .return_(id_("x").expr() + id_("y") + id_("z")) # set the expression to be returned and build the closure
        )
        assert closure.into_code() == "lambda x, y, z: x + y + z"
        ```
    """

    __args: list[Identifier]

    def __init__(self, *args: Identifier):
        """Initialize a closure.

        Args:
            *args: Initial closure argument list.
        """
        self.__args = list(args)

    def join(self, *args: Identifier) -> Self:
        """Append new arguments to the closure.

        Args:
            *args: New closure arguments.
        """
        self.__args.extend(args)
        return self

    def ret(self, e: expr.IntoExpression) -> Closure:
        """Set the expression to be returned by the closure.

        Args:
            e: expr.Expression to be returned.
        """
        return Closure(self.__args, e)

    def return_(self, e: expr.IntoExpression) -> Closure:
        """Alias [`ret`][synt.expr.closure.ClosureBuilder.ret]."""
        return self.ret(e)
__init__ ¤
__init__(*args: Identifier)

Initialize a closure.

Parameters:

Name Type Description Default
*args Identifier

Initial closure argument list.

()
Source code in synt/expr/closure.py
def __init__(self, *args: Identifier):
    """Initialize a closure.

    Args:
        *args: Initial closure argument list.
    """
    self.__args = list(args)
join ¤
join(*args: Identifier) -> Self

Append new arguments to the closure.

Parameters:

Name Type Description Default
*args Identifier

New closure arguments.

()
Source code in synt/expr/closure.py
def join(self, *args: Identifier) -> Self:
    """Append new arguments to the closure.

    Args:
        *args: New closure arguments.
    """
    self.__args.extend(args)
    return self
ret ¤

Set the expression to be returned by the closure.

Parameters:

Name Type Description Default
e IntoExpression

expr.Expression to be returned.

required
Source code in synt/expr/closure.py
def ret(self, e: expr.IntoExpression) -> Closure:
    """Set the expression to be returned by the closure.

    Args:
        e: expr.Expression to be returned.
    """
    return Closure(self.__args, e)
return_ ¤
return_(e: IntoExpression) -> Closure

Alias ret.

Source code in synt/expr/closure.py
def return_(self, e: expr.IntoExpression) -> Closure:
    """Alias [`ret`][synt.expr.closure.ClosureBuilder.ret]."""
    return self.ret(e)

comprehension ¤

Comprehension ¤

Bases: IntoExpression, IntoCode

A Comprehension expression.

Attribute explanation:

[
    a           # elt, aka "extract, load, transform"
                # 👇 generator node #1
    for b       # target
    in c        # iter
    if          # `if`s
        d == e  # an `if`

    for f in g  # 👈 generator node #2
]

Note: Comprehension is not a subclass of expr.Expression. However, it implements expr.IntoExpression, and will be internally converted into GeneratorComprehension.

References

comprehension.

Source code in synt/expr/comprehension.py
class Comprehension(expr.IntoExpression, code.IntoCode):
    r"""A Comprehension expression.

    **Attribute explanation:**
    ```python
    [
        a           # elt, aka "extract, load, transform"
                    # 👇 generator node #1
        for b       # target
        in c        # iter
        if          # `if`s
            d == e  # an `if`

        for f in g  # 👈 generator node #2
    ]
    ```

    **Note:**
    `Comprehension` is not a subclass of [`expr.Expression`][synt.expr.expr.Expression].
    However, it implements [`expr.IntoExpression`][synt.expr.expr.IntoExpression],
    and will be internally converted into [`GeneratorComprehension`][synt.expr.comprehension.GeneratorComprehension].

    References:
        [`comprehension`](https://docs.python.org/3/reference/
        expressions.html#grammar-tokens-python-grammar-comprehension).
    """

    elt: expr.Expression
    """The expression to evaluate when iterating over the
    [`iterator`][synt.expr.comprehension.ComprehensionNode.iterator].

    **Note:** aka "extract, load, transform"."""
    comprehensions: list[ComprehensionNode]
    """Generator nodes."""

    precedence = expr.ExprPrecedence.Atom

    def __init__(
        self,
        elt: expr.IntoExpression,
        comprehensions: list[ComprehensionNode],
    ):
        """Initialize a new comprehension expression.

        Args:
            elt: The expression to evaluate.
            comprehensions: The generator nodes.
        """
        self.elt = elt.into_expression()
        self.comprehensions = comprehensions

    def into_expression(self) -> GeneratorComprehension:
        return GeneratorComprehension(self)

    def into_code(self) -> str:
        comp_text = " ".join(x.into_code() for x in self.comprehensions)
        return f"{self.elt.into_code()} {comp_text}"
precedence class-attribute instance-attribute ¤
precedence = Atom
elt instance-attribute ¤
elt: Expression = into_expression()

The expression to evaluate when iterating over the iterator.

Note: aka "extract, load, transform".

comprehensions instance-attribute ¤

Generator nodes.

__init__ ¤
1
2
3
4
__init__(
    elt: IntoExpression,
    comprehensions: list[ComprehensionNode],
)

Initialize a new comprehension expression.

Parameters:

Name Type Description Default
elt IntoExpression

The expression to evaluate.

required
comprehensions list[ComprehensionNode]

The generator nodes.

required
Source code in synt/expr/comprehension.py
def __init__(
    self,
    elt: expr.IntoExpression,
    comprehensions: list[ComprehensionNode],
):
    """Initialize a new comprehension expression.

    Args:
        elt: The expression to evaluate.
        comprehensions: The generator nodes.
    """
    self.elt = elt.into_expression()
    self.comprehensions = comprehensions
into_expression ¤
into_expression() -> GeneratorComprehension
Source code in synt/expr/comprehension.py
def into_expression(self) -> GeneratorComprehension:
    return GeneratorComprehension(self)
into_code ¤
into_code() -> str
Source code in synt/expr/comprehension.py
def into_code(self) -> str:
    comp_text = " ".join(x.into_code() for x in self.comprehensions)
    return f"{self.elt.into_code()} {comp_text}"

ComprehensionNode ¤

Bases: IntoCode

Source code in synt/expr/comprehension.py
class ComprehensionNode(code.IntoCode):
    target: list[Identifier]
    """Comprehension `for`-loop target identifiers."""
    iterator: expr.Expression
    """The iterator to iterate over."""
    ifs: list[expr.Expression]
    """A list of `if` expressions to filter comprehension result."""
    is_async: bool
    """Whether the iterator is asynchronous."""

    precedence = expr.ExprPrecedence.Atom

    def __init__(
        self,
        target: list[Identifier],
        iterator: expr.IntoExpression,
        ifs: list[expr.IntoExpression],
        is_async: bool,
    ):
        """Initialize a new comprehension expression.

        Args:
            target: The target identifiers.
            iterator: The iterator to iterate over.
            ifs: A list of `if` expressions.
            is_async: Whether the iterator is asynchronous.
        """
        self.target = target
        self.iterator = iterator.into_expression()
        self.ifs = [x.into_expression() for x in ifs]
        self.is_async = is_async

    def into_code(self) -> str:
        target_text = ", ".join(t.into_code() for t in self.target)
        if self.ifs:
            if_text = " " + " ".join(f"if {i.into_code()}" for i in self.ifs)
        else:
            if_text = ""
        for_text = "async for" if self.is_async else "for"
        return f"{for_text} {target_text} in {self.iterator.into_code()}{if_text}"
precedence class-attribute instance-attribute ¤
precedence = Atom
target instance-attribute ¤
target: list[Identifier] = target

Comprehension for-loop target identifiers.

iterator instance-attribute ¤
iterator: Expression = into_expression()

The iterator to iterate over.

ifs instance-attribute ¤
ifs: list[Expression] = [into_expression() for x in ifs]

A list of if expressions to filter comprehension result.

is_async instance-attribute ¤
is_async: bool = is_async

Whether the iterator is asynchronous.

__init__ ¤
1
2
3
4
5
6
__init__(
    target: list[Identifier],
    iterator: IntoExpression,
    ifs: list[IntoExpression],
    is_async: bool,
)

Initialize a new comprehension expression.

Parameters:

Name Type Description Default
target list[Identifier]

The target identifiers.

required
iterator IntoExpression

The iterator to iterate over.

required
ifs list[IntoExpression]

A list of if expressions.

required
is_async bool

Whether the iterator is asynchronous.

required
Source code in synt/expr/comprehension.py
def __init__(
    self,
    target: list[Identifier],
    iterator: expr.IntoExpression,
    ifs: list[expr.IntoExpression],
    is_async: bool,
):
    """Initialize a new comprehension expression.

    Args:
        target: The target identifiers.
        iterator: The iterator to iterate over.
        ifs: A list of `if` expressions.
        is_async: Whether the iterator is asynchronous.
    """
    self.target = target
    self.iterator = iterator.into_expression()
    self.ifs = [x.into_expression() for x in ifs]
    self.is_async = is_async
into_code ¤
into_code() -> str
Source code in synt/expr/comprehension.py
def into_code(self) -> str:
    target_text = ", ".join(t.into_code() for t in self.target)
    if self.ifs:
        if_text = " " + " ".join(f"if {i.into_code()}" for i in self.ifs)
    else:
        if_text = ""
    for_text = "async for" if self.is_async else "for"
    return f"{for_text} {target_text} in {self.iterator.into_code()}{if_text}"

GeneratorComprehension ¤

Bases: Expression

A generator comprehension expression.

Note: GeneratorComprehension is a subclass of expr.Expression, working as a wrapper for Comprehension.

Source code in synt/expr/comprehension.py
class GeneratorComprehension(expr.Expression):
    r"""A generator comprehension expression.

    **Note:**
    `GeneratorComprehension` is a subclass of [`expr.Expression`][synt.expr.expr.Expression],
    working as a wrapper for [`Comprehension`][synt.expr.comprehension.Comprehension].
    """

    comprehension: Comprehension
    """The inner comprehension expression."""

    precedence = expr.ExprPrecedence.Atom
    expr_type = expr.ExprType.Comprehension

    def __init__(self, comprehension: Comprehension):
        """Initialize a generator comprehension expression.

        Args:
            comprehension: The inner comprehension expression to wrap.
        """
        self.comprehension = comprehension

    def into_code(self) -> str:
        return f"({self.comprehension.into_code()})"
precedence class-attribute instance-attribute ¤
precedence = Atom
expr_type class-attribute instance-attribute ¤
expr_type = Comprehension
comprehension instance-attribute ¤
comprehension: Comprehension = comprehension

The inner comprehension expression.

__init__ ¤
__init__(comprehension: Comprehension)

Initialize a generator comprehension expression.

Parameters:

Name Type Description Default
comprehension Comprehension

The inner comprehension expression to wrap.

required
Source code in synt/expr/comprehension.py
def __init__(self, comprehension: Comprehension):
    """Initialize a generator comprehension expression.

    Args:
        comprehension: The inner comprehension expression to wrap.
    """
    self.comprehension = comprehension
into_code ¤
into_code() -> str
Source code in synt/expr/comprehension.py
def into_code(self) -> str:
    return f"({self.comprehension.into_code()})"

ComprehensionBuilder ¤

Bases: IntoExpression

Builder for Comprehension.

Source code in synt/expr/comprehension.py
class ComprehensionBuilder(expr.IntoExpression):
    r"""Builder for [`Comprehension`][synt.expr.comprehension.Comprehension]."""

    __elt: expr.Expression
    __comprehensions: list[ComprehensionNode]
    __curr_node: ComprehensionNodeBuilder | None

    def __init__(
        self,
        elt: expr.IntoExpression,
        target: list[ident.Identifier],
        is_async: bool = False,
    ):
        """Initialize a generator comprehension expression.

        Args:
            elt: The expression to evaluate.
            target: The target of the iteration.
            is_async: Whether the comprehension is asynchronous.
        """
        self.__elt = elt.into_expression()
        self.__comprehensions = []
        self.__curr_node = ComprehensionNodeBuilder(self, is_async).target(*target)

    @staticmethod
    def init(
        elt: expr.IntoExpression, target: list[ident.Identifier], is_async: bool = False
    ) -> ComprehensionNodeBuilder:
        """Initialize a generator comprehension expression and return the first node builder.

        Args:
            elt: The expression to evaluate.
            target: The target of the iteration.
            is_async: Whether the comprehension is asynchronous.
        """
        return ComprehensionBuilder(elt, target, is_async).curr_node()  # type:ignore[return-value]

    def curr_node(self) -> ComprehensionNodeBuilder | None:
        """Returns the current node builder."""
        return self.__curr_node

    def __finish_node_builder(self) -> None:
        if self.__curr_node:
            res = self.__curr_node.build()
            self.__comprehensions.append(res)
            self.__curr_node = None

    def for_(self, iterator: expr.IntoExpression) -> ComprehensionNodeBuilder:
        """Create a new comprehension node.

        This will finish the previous [`ComprehensionNodeBuilder`][synt.expr.comprehension.ComprehensionNodeBuilder]
        and start a new one.
        """
        self.__finish_node_builder()
        return ComprehensionNodeBuilder(self).iterator(iterator)

    def async_for(self, iterator: expr.IntoExpression) -> ComprehensionNodeBuilder:
        """Create a new async comprehension node.

        This will finish the previous [`ComprehensionNodeBuilder`][synt.expr.comprehension.ComprehensionNodeBuilder]
        and start a new one.
        """
        self.__finish_node_builder()
        return ComprehensionNodeBuilder(self, True).iterator(iterator)

    def build(self) -> Comprehension:
        """Build the comprehension expression.

        Raises:
            ValueError: If any required fields are missing.
        """
        self.__finish_node_builder()
        return Comprehension(self.__elt, self.__comprehensions)

    def into_expression(self) -> GeneratorComprehension:
        return self.build().into_expression()
__init__ ¤
1
2
3
4
5
__init__(
    elt: IntoExpression,
    target: list[Identifier],
    is_async: bool = False,
)

Initialize a generator comprehension expression.

Parameters:

Name Type Description Default
elt IntoExpression

The expression to evaluate.

required
target list[Identifier]

The target of the iteration.

required
is_async bool

Whether the comprehension is asynchronous.

False
Source code in synt/expr/comprehension.py
def __init__(
    self,
    elt: expr.IntoExpression,
    target: list[ident.Identifier],
    is_async: bool = False,
):
    """Initialize a generator comprehension expression.

    Args:
        elt: The expression to evaluate.
        target: The target of the iteration.
        is_async: Whether the comprehension is asynchronous.
    """
    self.__elt = elt.into_expression()
    self.__comprehensions = []
    self.__curr_node = ComprehensionNodeBuilder(self, is_async).target(*target)
init staticmethod ¤
1
2
3
4
5
init(
    elt: IntoExpression,
    target: list[Identifier],
    is_async: bool = False,
) -> ComprehensionNodeBuilder

Initialize a generator comprehension expression and return the first node builder.

Parameters:

Name Type Description Default
elt IntoExpression

The expression to evaluate.

required
target list[Identifier]

The target of the iteration.

required
is_async bool

Whether the comprehension is asynchronous.

False
Source code in synt/expr/comprehension.py
@staticmethod
def init(
    elt: expr.IntoExpression, target: list[ident.Identifier], is_async: bool = False
) -> ComprehensionNodeBuilder:
    """Initialize a generator comprehension expression and return the first node builder.

    Args:
        elt: The expression to evaluate.
        target: The target of the iteration.
        is_async: Whether the comprehension is asynchronous.
    """
    return ComprehensionBuilder(elt, target, is_async).curr_node()  # type:ignore[return-value]
curr_node ¤
curr_node() -> ComprehensionNodeBuilder | None

Returns the current node builder.

Source code in synt/expr/comprehension.py
def curr_node(self) -> ComprehensionNodeBuilder | None:
    """Returns the current node builder."""
    return self.__curr_node
for_ ¤

Create a new comprehension node.

This will finish the previous ComprehensionNodeBuilder and start a new one.

Source code in synt/expr/comprehension.py
def for_(self, iterator: expr.IntoExpression) -> ComprehensionNodeBuilder:
    """Create a new comprehension node.

    This will finish the previous [`ComprehensionNodeBuilder`][synt.expr.comprehension.ComprehensionNodeBuilder]
    and start a new one.
    """
    self.__finish_node_builder()
    return ComprehensionNodeBuilder(self).iterator(iterator)
async_for ¤
1
2
3
async_for(
    iterator: IntoExpression,
) -> ComprehensionNodeBuilder

Create a new async comprehension node.

This will finish the previous ComprehensionNodeBuilder and start a new one.

Source code in synt/expr/comprehension.py
def async_for(self, iterator: expr.IntoExpression) -> ComprehensionNodeBuilder:
    """Create a new async comprehension node.

    This will finish the previous [`ComprehensionNodeBuilder`][synt.expr.comprehension.ComprehensionNodeBuilder]
    and start a new one.
    """
    self.__finish_node_builder()
    return ComprehensionNodeBuilder(self, True).iterator(iterator)
build ¤
build() -> Comprehension

Build the comprehension expression.

Raises:

Type Description
ValueError

If any required fields are missing.

Source code in synt/expr/comprehension.py
def build(self) -> Comprehension:
    """Build the comprehension expression.

    Raises:
        ValueError: If any required fields are missing.
    """
    self.__finish_node_builder()
    return Comprehension(self.__elt, self.__comprehensions)
into_expression ¤
into_expression() -> GeneratorComprehension
Source code in synt/expr/comprehension.py
def into_expression(self) -> GeneratorComprehension:
    return self.build().into_expression()

ComprehensionNodeBuilder ¤

Bases: IntoExpression

Builder for ComprehensionNode.

Source code in synt/expr/comprehension.py
class ComprehensionNodeBuilder(expr.IntoExpression):
    r"""Builder for [`ComprehensionNode`][synt.expr.comprehension.ComprehensionNode]."""

    __target: list[Identifier] | None
    __iterator: expr.Expression | None
    __ifs: list[expr.IntoExpression]
    __is_async: bool = False

    def __init__(self, root: ComprehensionBuilder, is_async: bool = False):
        """Initialize an empty builder.

        Args:
            root: The root builder.
            is_async: Whether the comprehension is asynchronous.
        """
        self.root = root
        self.__is_async = is_async
        self.__target = None
        self.__iterator = None
        self.__ifs = []

    def target(self, *target: Identifier) -> Self:
        """Set the target of the comprehension generator.

        Args:
            target: The target identifiers.
        """
        self.__target = list(target)
        return self

    def in_(self, iterator: expr.IntoExpression) -> Self:
        """Alias [`iterator`][synt.expr.comprehension.ComprehensionNodeBuilder.iterator]."""
        return self.iterator(iterator)

    def iterator(self, iterator: expr.IntoExpression) -> Self:
        """Set the iterator of the comprehension generator.

        Args:
            iterator: The iterator to iterate over.
        """
        self.__iterator = iterator.into_expression()
        return self

    def if_(self, if_expr: expr.IntoExpression) -> Self:
        """Add an `if` expression to filter comprehension result.

        Args:
            if_expr: The `if` expression.
        """
        self.__ifs.append(if_expr.into_expression())
        return self

    def async_(self) -> Self:
        """Set the comprehension as asynchronous."""
        self.__is_async = True
        return self

    def sync(self) -> Self:
        """Set the comprehension as synchronous."""
        self.__is_async = False
        return self

    def build(self) -> ComprehensionNode:
        """Build the comprehension node.

        Raises:
            ValueError: If any required fields are missing.
        """
        err_fields = []
        if self.__iterator is None:
            err_fields.append("iterator")
        if not self.__target:
            err_fields.append("target")

        if err_fields:
            raise ValueError(
                f"Missing required fields: {', '.join(f'`{t}`' for t in err_fields)}"
            )
        return ComprehensionNode(
            self.__target,  # type:ignore[arg-type]
            self.__iterator,  # type:ignore[arg-type]
            self.__ifs,
            self.__is_async,
        )

    def for_(self, iterator: expr.IntoExpression) -> ComprehensionNodeBuilder:
        """Create a new comprehension node.

        This will call root's [`for_`][synt.expr.comprehension.ComprehensionBuilder.for_].
        """
        return self.root.for_(iterator)

    def async_for(self, iterator: expr.IntoExpression) -> ComprehensionNodeBuilder:
        """Create a new async comprehension node.

        This will call root's [`async_for`][synt.expr.comprehension.ComprehensionBuilder.async_for].
        """
        return self.root.async_for(iterator)

    def build_comp(self) -> Comprehension:
        """Build the comprehension expression.

        Raises:
            ValueError: If any required fields are missing.
        """
        return self.root.build()

    def into_expression(self) -> GeneratorComprehension:
        return self.build_comp().into_expression()
root instance-attribute ¤
root = root
__init__ ¤
1
2
3
__init__(
    root: ComprehensionBuilder, is_async: bool = False
)

Initialize an empty builder.

Parameters:

Name Type Description Default
root ComprehensionBuilder

The root builder.

required
is_async bool

Whether the comprehension is asynchronous.

False
Source code in synt/expr/comprehension.py
def __init__(self, root: ComprehensionBuilder, is_async: bool = False):
    """Initialize an empty builder.

    Args:
        root: The root builder.
        is_async: Whether the comprehension is asynchronous.
    """
    self.root = root
    self.__is_async = is_async
    self.__target = None
    self.__iterator = None
    self.__ifs = []
target ¤
target(*target: Identifier) -> Self

Set the target of the comprehension generator.

Parameters:

Name Type Description Default
target Identifier

The target identifiers.

()
Source code in synt/expr/comprehension.py
def target(self, *target: Identifier) -> Self:
    """Set the target of the comprehension generator.

    Args:
        target: The target identifiers.
    """
    self.__target = list(target)
    return self
in_ ¤
in_(iterator: IntoExpression) -> Self

Alias iterator.

Source code in synt/expr/comprehension.py
def in_(self, iterator: expr.IntoExpression) -> Self:
    """Alias [`iterator`][synt.expr.comprehension.ComprehensionNodeBuilder.iterator]."""
    return self.iterator(iterator)
iterator ¤
iterator(iterator: IntoExpression) -> Self

Set the iterator of the comprehension generator.

Parameters:

Name Type Description Default
iterator IntoExpression

The iterator to iterate over.

required
Source code in synt/expr/comprehension.py
def iterator(self, iterator: expr.IntoExpression) -> Self:
    """Set the iterator of the comprehension generator.

    Args:
        iterator: The iterator to iterate over.
    """
    self.__iterator = iterator.into_expression()
    return self
if_ ¤
if_(if_expr: IntoExpression) -> Self

Add an if expression to filter comprehension result.

Parameters:

Name Type Description Default
if_expr IntoExpression

The if expression.

required
Source code in synt/expr/comprehension.py
def if_(self, if_expr: expr.IntoExpression) -> Self:
    """Add an `if` expression to filter comprehension result.

    Args:
        if_expr: The `if` expression.
    """
    self.__ifs.append(if_expr.into_expression())
    return self
async_ ¤
async_() -> Self

Set the comprehension as asynchronous.

Source code in synt/expr/comprehension.py
def async_(self) -> Self:
    """Set the comprehension as asynchronous."""
    self.__is_async = True
    return self
sync ¤
sync() -> Self

Set the comprehension as synchronous.

Source code in synt/expr/comprehension.py
def sync(self) -> Self:
    """Set the comprehension as synchronous."""
    self.__is_async = False
    return self
build ¤
build() -> ComprehensionNode

Build the comprehension node.

Raises:

Type Description
ValueError

If any required fields are missing.

Source code in synt/expr/comprehension.py
def build(self) -> ComprehensionNode:
    """Build the comprehension node.

    Raises:
        ValueError: If any required fields are missing.
    """
    err_fields = []
    if self.__iterator is None:
        err_fields.append("iterator")
    if not self.__target:
        err_fields.append("target")

    if err_fields:
        raise ValueError(
            f"Missing required fields: {', '.join(f'`{t}`' for t in err_fields)}"
        )
    return ComprehensionNode(
        self.__target,  # type:ignore[arg-type]
        self.__iterator,  # type:ignore[arg-type]
        self.__ifs,
        self.__is_async,
    )
for_ ¤

Create a new comprehension node.

This will call root's for_.

Source code in synt/expr/comprehension.py
def for_(self, iterator: expr.IntoExpression) -> ComprehensionNodeBuilder:
    """Create a new comprehension node.

    This will call root's [`for_`][synt.expr.comprehension.ComprehensionBuilder.for_].
    """
    return self.root.for_(iterator)
async_for ¤
1
2
3
async_for(
    iterator: IntoExpression,
) -> ComprehensionNodeBuilder

Create a new async comprehension node.

This will call root's async_for.

Source code in synt/expr/comprehension.py
def async_for(self, iterator: expr.IntoExpression) -> ComprehensionNodeBuilder:
    """Create a new async comprehension node.

    This will call root's [`async_for`][synt.expr.comprehension.ComprehensionBuilder.async_for].
    """
    return self.root.async_for(iterator)
build_comp ¤
build_comp() -> Comprehension

Build the comprehension expression.

Raises:

Type Description
ValueError

If any required fields are missing.

Source code in synt/expr/comprehension.py
def build_comp(self) -> Comprehension:
    """Build the comprehension expression.

    Raises:
        ValueError: If any required fields are missing.
    """
    return self.root.build()
into_expression ¤
into_expression() -> GeneratorComprehension
Source code in synt/expr/comprehension.py
def into_expression(self) -> GeneratorComprehension:
    return self.build_comp().into_expression()

condition ¤

Condition ¤

Bases: Expression

Conditional expression, aka if - else.

References

expr.ExprPrecedence.Conditional.

Source code in synt/expr/condition.py
class Condition(expr.Expression):
    r"""Conditional expression, aka `if - else`.

    References:
        [expr.ExprPrecedence.Conditional][synt.expr.expr.ExprPrecedence.Conditional].
    """

    condition: expr.Expression
    """Condition expression."""
    true_expr: expr.Expression
    """expr.Expression to evaluate and return if the condition is true."""
    false_expr: expr.Expression
    """expr.Expression to evaluate and return if the condition is false."""
    precedence = expr.ExprPrecedence.Conditional
    expr_type = expr.ExprType.Condition

    def __init__(
        self,
        condition: expr.IntoExpression,
        true_expr: expr.IntoExpression,
        false_expr: expr.IntoExpression,
    ):
        """Initialize a new conditional expression.

        Args:
            condition: Condition expression.
            true_expr: expr.Expression to evaluate and return if the condition is true.
            false_expr: expr.Expression to evaluate and return if the condition is false.
        """
        self.condition = condition.into_expression()
        if self.condition.precedence > self.precedence:
            self.condition = self.condition.wrapped()
        self.true_expr = true_expr.into_expression()
        if self.true_expr.precedence > self.precedence:
            self.true_expr = self.true_expr.wrapped()
        self.false_expr = false_expr.into_expression()
        if self.false_expr.precedence > self.precedence:
            self.false_expr = self.false_expr.wrapped()

    def into_code(self) -> str:
        return f"{self.true_expr.into_code()} if {self.condition.into_code()} else {self.false_expr.into_code()}"
precedence class-attribute instance-attribute ¤
precedence = Conditional
expr_type class-attribute instance-attribute ¤
expr_type = Condition
condition instance-attribute ¤
condition: Expression = into_expression()

Condition expression.

true_expr instance-attribute ¤
true_expr: Expression = into_expression()

expr.Expression to evaluate and return if the condition is true.

false_expr instance-attribute ¤
false_expr: Expression = into_expression()

expr.Expression to evaluate and return if the condition is false.

__init__ ¤
1
2
3
4
5
__init__(
    condition: IntoExpression,
    true_expr: IntoExpression,
    false_expr: IntoExpression,
)

Initialize a new conditional expression.

Parameters:

Name Type Description Default
condition IntoExpression

Condition expression.

required
true_expr IntoExpression

expr.Expression to evaluate and return if the condition is true.

required
false_expr IntoExpression

expr.Expression to evaluate and return if the condition is false.

required
Source code in synt/expr/condition.py
def __init__(
    self,
    condition: expr.IntoExpression,
    true_expr: expr.IntoExpression,
    false_expr: expr.IntoExpression,
):
    """Initialize a new conditional expression.

    Args:
        condition: Condition expression.
        true_expr: expr.Expression to evaluate and return if the condition is true.
        false_expr: expr.Expression to evaluate and return if the condition is false.
    """
    self.condition = condition.into_expression()
    if self.condition.precedence > self.precedence:
        self.condition = self.condition.wrapped()
    self.true_expr = true_expr.into_expression()
    if self.true_expr.precedence > self.precedence:
        self.true_expr = self.true_expr.wrapped()
    self.false_expr = false_expr.into_expression()
    if self.false_expr.precedence > self.precedence:
        self.false_expr = self.false_expr.wrapped()
into_code ¤
into_code() -> str
Source code in synt/expr/condition.py
def into_code(self) -> str:
    return f"{self.true_expr.into_code()} if {self.condition.into_code()} else {self.false_expr.into_code()}"

ConditionBuilder ¤

Builder for Condition.

Source code in synt/expr/condition.py
class ConditionBuilder:
    r"""Builder for [`Condition`][synt.expr.condition.Condition]."""

    __condition: expr.Expression
    __true_expr: expr.Expression
    __false_expr: expr.Expression | None

    def __init__(self, condition: expr.IntoExpression, true_expr: expr.IntoExpression):
        """Initialize an empty condition builder.

        Args:
            condition: Condition expression.
            true_expr: expr.Expression to evaluate if the condition is true.
        """
        self.__condition = condition.into_expression()
        self.__true_expr = true_expr.into_expression()
        self.__false_expr = None

    def false_expr(self, e: expr.IntoExpression) -> Self:
        """Set the expression to evaluate if the condition is false.

        Args:
            e: expr.Expression to evaluate.
        """
        self.__false_expr = e.into_expression()
        return self

    def build(self) -> Condition:
        """Build the condition.

        Raises:
            ValueError: If any of the required field is empty.
        """
        err_fields = []
        if self.__false_expr is None:
            err_fields.append("false_expr")

        if err_fields:
            raise ValueError(
                f"Missing required field(s): {', '.join(f'`{t}`' for t in err_fields)}"
            )
        return Condition(self.__condition, self.__true_expr, self.__false_expr)  # type:ignore[arg-type]

    def else_(self, other: expr.IntoExpression) -> Condition:
        """Set the `false_expr` and build the builder.

        Args:
            other: expr.Expression to evaluate if the condition is false.

        Raises:
            ValueError: If any of the required field is empty.
        """
        self.false_expr(other)
        return self.build()
__init__ ¤
1
2
3
__init__(
    condition: IntoExpression, true_expr: IntoExpression
)

Initialize an empty condition builder.

Parameters:

Name Type Description Default
condition IntoExpression

Condition expression.

required
true_expr IntoExpression

expr.Expression to evaluate if the condition is true.

required
Source code in synt/expr/condition.py
def __init__(self, condition: expr.IntoExpression, true_expr: expr.IntoExpression):
    """Initialize an empty condition builder.

    Args:
        condition: Condition expression.
        true_expr: expr.Expression to evaluate if the condition is true.
    """
    self.__condition = condition.into_expression()
    self.__true_expr = true_expr.into_expression()
    self.__false_expr = None
false_expr ¤
false_expr(e: IntoExpression) -> Self

Set the expression to evaluate if the condition is false.

Parameters:

Name Type Description Default
e IntoExpression

expr.Expression to evaluate.

required
Source code in synt/expr/condition.py
def false_expr(self, e: expr.IntoExpression) -> Self:
    """Set the expression to evaluate if the condition is false.

    Args:
        e: expr.Expression to evaluate.
    """
    self.__false_expr = e.into_expression()
    return self
build ¤
build() -> Condition

Build the condition.

Raises:

Type Description
ValueError

If any of the required field is empty.

Source code in synt/expr/condition.py
def build(self) -> Condition:
    """Build the condition.

    Raises:
        ValueError: If any of the required field is empty.
    """
    err_fields = []
    if self.__false_expr is None:
        err_fields.append("false_expr")

    if err_fields:
        raise ValueError(
            f"Missing required field(s): {', '.join(f'`{t}`' for t in err_fields)}"
        )
    return Condition(self.__condition, self.__true_expr, self.__false_expr)  # type:ignore[arg-type]
else_ ¤
else_(other: IntoExpression) -> Condition

Set the false_expr and build the builder.

Parameters:

Name Type Description Default
other IntoExpression

expr.Expression to evaluate if the condition is false.

required

Raises:

Type Description
ValueError

If any of the required field is empty.

Source code in synt/expr/condition.py
def else_(self, other: expr.IntoExpression) -> Condition:
    """Set the `false_expr` and build the builder.

    Args:
        other: expr.Expression to evaluate if the condition is false.

    Raises:
        ValueError: If any of the required field is empty.
    """
    self.false_expr(other)
    return self.build()

dict ¤

dict_ module-attribute ¤

dict_ = DictVerbatim

Alias DictVerbatim.

Notes

dict is a built-in type in Python, so it's renamed to dict_ with a suffix.

dict_comp module-attribute ¤

dict_comp = DictComprehension

DictDisplay ¤

Bases: Expression

Literal dict expression.

References

Dictionary display.

Source code in synt/expr/dict.py
class DictDisplay(expr.Expression, metaclass=ABCMeta):
    r"""Literal dict expression.

    References:
        [Dictionary display](https://docs.python.org/3/reference/expressions.html#dictionary-displays).
    """

    precedence = expr.ExprPrecedence.Atom
    expr_type = expr.ExprType.Dict
precedence class-attribute instance-attribute ¤
precedence = Atom
expr_type class-attribute instance-attribute ¤
expr_type = Dict

DictVerbatim ¤

Bases: DictDisplay

Verbatim dict expression.

Examples:

d = dict_(kv(litstr("a"), id_("b")))
assert d.into_code() == "{'a': b}"
Source code in synt/expr/dict.py
class DictVerbatim(DictDisplay):
    r"""Verbatim dict expression.

    Examples:
        ```python
        d = dict_(kv(litstr("a"), id_("b")))
        assert d.into_code() == "{'a': b}"
        ```
    """

    items: list[KVPair]
    """Dict items."""

    def __init__(self, *items: KVPair):
        """Initialize a new verbatim dict expression.

        Args:
            items: dictionary items.
        """
        self.items = list(items)

    def into_code(self) -> str:
        item_text = ", ".join(x.into_code() for x in self.items)
        return f"{{{item_text}}}"
items instance-attribute ¤
items: list[KVPair] = list(items)

Dict items.

__init__ ¤
__init__(*items: KVPair)

Initialize a new verbatim dict expression.

Parameters:

Name Type Description Default
items KVPair

dictionary items.

()
Source code in synt/expr/dict.py
def __init__(self, *items: KVPair):
    """Initialize a new verbatim dict expression.

    Args:
        items: dictionary items.
    """
    self.items = list(items)
into_code ¤
into_code() -> str
Source code in synt/expr/dict.py
def into_code(self) -> str:
    item_text = ", ".join(x.into_code() for x in self.items)
    return f"{{{item_text}}}"

DictComprehension ¤

Bases: DictDisplay

Dict comprehension expression.

Note that you can also directly insert a comprehension expression into a normal dictionary, but that will become a generator comprehension and returns a pair of extra parenthesis.

Examples:

d = dict_comp(kv(id_("a"), litint(1)).for_(id_("a")).in_(id_("range").call(litint(5)))
assert d.into_code() == "{a: 1 for a in range(5)}"
References

comprehension.

Source code in synt/expr/dict.py
class DictComprehension(DictDisplay):
    r"""Dict comprehension expression.

    Note that you can also directly insert a comprehension expression into a normal dictionary,
    but that will become a generator comprehension and returns a pair of extra parenthesis.

    Examples:
        ```python
        d = dict_comp(kv(id_("a"), litint(1)).for_(id_("a")).in_(id_("range").call(litint(5)))
        assert d.into_code() == "{a: 1 for a in range(5)}"
        ```

    References:
        [`comprehension`](https://docs.python.org/3/reference/
        expressions.html#grammar-tokens-python-grammar-comprehension).
    """

    comprehension: comp_expr.Comprehension
    """Internal comprehension expression."""

    def __init__(
        self,
        comprehension: comp_expr.Comprehension
        | comp_expr.ComprehensionBuilder
        | comp_expr.ComprehensionNodeBuilder,
    ):
        """Initialize a new dict comprehension expression.

        Args:
            comprehension: Internal comprehension expression.

        Raises:
            ExpressionTypeException: Invalid dict comprehension result type,
                typically not a [`KVPair`][synt.tokens.kv_pair.KVPair].
        """
        if isinstance(comprehension, comp_expr.Comprehension):
            comp = comprehension
        elif isinstance(comprehension, comp_expr.ComprehensionBuilder):
            comp = comprehension.build()
        elif isinstance(comprehension, comp_expr.ComprehensionNodeBuilder):
            comp = comprehension.build_comp()
        else:
            raise ValueError(
                "Expect expression of type `Comprehension`, found `Unknown`."
            )

        if comp.elt.expr_type != expr.ExprType.KeyValuePair:
            raise ValueError(
                "Expect expression of type `KeyValuePair`, found `Unknown`."
            )
        self.comprehension = comp

    def into_code(self) -> str:
        return f"{{{self.comprehension.into_code()}}}"
comprehension instance-attribute ¤
comprehension: Comprehension = comp

Internal comprehension expression.

__init__ ¤
1
2
3
4
5
6
7
__init__(
    comprehension: (
        Comprehension
        | ComprehensionBuilder
        | ComprehensionNodeBuilder
    ),
)

Initialize a new dict comprehension expression.

Parameters:

Name Type Description Default
comprehension Comprehension | ComprehensionBuilder | ComprehensionNodeBuilder

Internal comprehension expression.

required

Raises:

Type Description
ExpressionTypeException

Invalid dict comprehension result type, typically not a KVPair.

Source code in synt/expr/dict.py
def __init__(
    self,
    comprehension: comp_expr.Comprehension
    | comp_expr.ComprehensionBuilder
    | comp_expr.ComprehensionNodeBuilder,
):
    """Initialize a new dict comprehension expression.

    Args:
        comprehension: Internal comprehension expression.

    Raises:
        ExpressionTypeException: Invalid dict comprehension result type,
            typically not a [`KVPair`][synt.tokens.kv_pair.KVPair].
    """
    if isinstance(comprehension, comp_expr.Comprehension):
        comp = comprehension
    elif isinstance(comprehension, comp_expr.ComprehensionBuilder):
        comp = comprehension.build()
    elif isinstance(comprehension, comp_expr.ComprehensionNodeBuilder):
        comp = comprehension.build_comp()
    else:
        raise ValueError(
            "Expect expression of type `Comprehension`, found `Unknown`."
        )

    if comp.elt.expr_type != expr.ExprType.KeyValuePair:
        raise ValueError(
            "Expect expression of type `KeyValuePair`, found `Unknown`."
        )
    self.comprehension = comp
into_code ¤
into_code() -> str
Source code in synt/expr/dict.py
def into_code(self) -> str:
    return f"{{{self.comprehension.into_code()}}}"

empty ¤

empty module-attribute ¤

empty = Empty

Alias Empty.

expr module-attribute ¤

expr = Empty

Alias Empty.

null module-attribute ¤

null = Empty

Alias Empty.

EMPTY module-attribute ¤

EMPTY = Empty()

An instance of Empty.

NULL module-attribute ¤

NULL = Empty()

An instance of Empty.

Empty ¤

Bases: Expression

Empty expression.

References

expr.ExprType.Empty.

Source code in synt/expr/empty.py
class Empty(syn_expr.Expression):
    r"""Empty expression.

    References:
        [expr.ExprType.Empty][synt.expr.expr.ExprType.Empty].
    """

    precedence = syn_expr.ExprPrecedence.Atom
    expr_type = syn_expr.ExprType.Identifier

    def __init__(self) -> None:
        pass

    def into_code(self) -> str:
        return ""
precedence class-attribute instance-attribute ¤
precedence = Atom
expr_type class-attribute instance-attribute ¤
expr_type = Identifier
__init__ ¤
__init__() -> None
Source code in synt/expr/empty.py
def __init__(self) -> None:
    pass
into_code ¤
into_code() -> str
Source code in synt/expr/empty.py
def into_code(self) -> str:
    return ""

expr ¤

ExprPrecedence ¤

Bases: IntEnum

Python's expression precedence.

Sort sequence: smaller = prior

References

Operator precedence

Source code in synt/expr/expr.py
class ExprPrecedence(IntEnum):
    r"""Python's expression precedence.

    Sort sequence: smaller = prior

    References:
        [Operator precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence)
    """

    Atom = 0
    """Atom expression: Binding or parenthesized expression, list display, dictionary display, set display,
    and other bound operations.

    Examples:
        ```python
        (expressions...)  # tuple / bind
        [expressions...]  # list
        {key: value...}   # dict
        {expressions...}  # set
        **kwargs          # bound operations (unpacking)
        x for x in y      # bound expressions (generator comprehension)
        yield from tasks  # bound expressions (yield / yield from)
        ```
    """

    Call = 1
    """call.Call-like: subscription, slicing, call, attribute reference.

    Examples:
        ```python
        x[index]       # subscribe
        x[index:index] # slice
        x(args, ...)   # call
        x.attr         # attribute
        ```
    """

    Await = 2
    """Await expression.

    Examples:
        ```python
        await x
        ```
    """

    Exponential = 3
    """Exponential operation: exponentiation.

    **Exception:**
    The power operator `**` binds less tightly than an arithmetic or bitwise unary operator on its right,
    that is, `2 ** -1` is `0.5`.

    Examples:
        ```python
        x ** y
        ```
    """

    Unary = 4
    """Unary operator: positive, negative, bitwise NOT.

    Examples:
        ```python
        +x  # positive
        -x  # negative
        ~x  # bitwise NOT
        ```
    """

    Multiplicative = 5
    """Multiplicative operation: multiplication, matrix multiplication, division, floor division, remainder.

    Notes:
        The `%` operator is also used for string formatting; the same precedence applies.

    Examples:
        ```python
        x * y   # multiplication
        x @ y   # matrix multiplication
        x / y   # division
        x // y  # floor division
        x % y   # remainder
        ```
    """

    Additive = 6
    """Additive operation: addition and subtraction.

    Examples:
        ```python
        x + y  # addition
        x - y  # subtraction
        ```
    """

    Shift = 7
    """Shift operation.

    Examples:
        ```python
        x << y  # left shift
        x >> y  # right shift
        ```
    """

    BitAnd = 8
    """Bitwise AND.

    Examples:
        ```python
        x & y  # bitwise AND
        ```
    """

    BitXor = 9
    """Bitwise XOR.

    Examples:
        ```python
        x ^ y  # bitwise XOR
        ```
    """

    BitOr = 10
    """Bitwise OR.

    Examples:
        ```python
        x | y  # bitwise OR
        ```
    """

    Comparative = 11
    """Boolean operations: comparisons, including membership tests and identity tests.

    Examples:
        ```python
        x in y          # membership tests
        x not in y
        x is y          # identity tests
        x is not y
        x < y           # comparisons
        x <= y
        x > y
        x >= y
        x != y
        x == y
        ```
    """

    BoolNot = 12
    """Boolean NOT.

    Examples:
        ```python
        not x  # boolean NOT
        ```
    """

    BoolAnd = 13
    """Boolean AND.

    Examples:
        ```python
        x and y  # boolean AND
        ```
    """

    BoolOr = 14
    """Boolean OR.

    Examples:
        ```python
        x or y  # boolean OR
        ```
    """

    Conditional = 15
    """Conditional expression: `if` - `else` expression.

    Examples:
        ```python
        x if condition else y
        ```
    """

    Lambda = 16
    """Lambda expression.

    Examples:
        ```python
        lambda x, y: x + y
        ```
    """

    NamedExpr = 17
    """Inline assignment expression.

    Examples:
        ```python
        x := y
        ```
    """
Atom class-attribute instance-attribute ¤
Atom = 0

Atom expression: Binding or parenthesized expression, list display, dictionary display, set display, and other bound operations.

Examples:

1
2
3
4
5
6
7
(expressions...)  # tuple / bind
[expressions...]  # list
{key: value...}   # dict
{expressions...}  # set
**kwargs          # bound operations (unpacking)
x for x in y      # bound expressions (generator comprehension)
yield from tasks  # bound expressions (yield / yield from)
Call class-attribute instance-attribute ¤
Call = 1

call.Call-like: subscription, slicing, call, attribute reference.

Examples:

1
2
3
4
x[index]       # subscribe
x[index:index] # slice
x(args, ...)   # call
x.attr         # attribute
Await class-attribute instance-attribute ¤
Await = 2

Await expression.

Examples:

await x
Exponential class-attribute instance-attribute ¤
Exponential = 3

Exponential operation: exponentiation.

Exception: The power operator ** binds less tightly than an arithmetic or bitwise unary operator on its right, that is, 2 ** -1 is 0.5.

Examples:

x ** y
Unary class-attribute instance-attribute ¤
Unary = 4

Unary operator: positive, negative, bitwise NOT.

Examples:

1
2
3
+x  # positive
-x  # negative
~x  # bitwise NOT
Multiplicative class-attribute instance-attribute ¤
Multiplicative = 5

Multiplicative operation: multiplication, matrix multiplication, division, floor division, remainder.

Notes

The % operator is also used for string formatting; the same precedence applies.

Examples:

1
2
3
4
5
x * y   # multiplication
x @ y   # matrix multiplication
x / y   # division
x // y  # floor division
x % y   # remainder
Additive class-attribute instance-attribute ¤
Additive = 6

Additive operation: addition and subtraction.

Examples:

x + y  # addition
x - y  # subtraction
Shift class-attribute instance-attribute ¤
Shift = 7

Shift operation.

Examples:

x << y  # left shift
x >> y  # right shift
BitAnd class-attribute instance-attribute ¤
BitAnd = 8

Bitwise AND.

Examples:

x & y  # bitwise AND
BitXor class-attribute instance-attribute ¤
BitXor = 9

Bitwise XOR.

Examples:

x ^ y  # bitwise XOR
BitOr class-attribute instance-attribute ¤
BitOr = 10

Bitwise OR.

Examples:

x | y  # bitwise OR
Comparative class-attribute instance-attribute ¤
Comparative = 11

Boolean operations: comparisons, including membership tests and identity tests.

Examples:

x in y          # membership tests
x not in y
x is y          # identity tests
x is not y
x < y           # comparisons
x <= y
x > y
x >= y
x != y
x == y
BoolNot class-attribute instance-attribute ¤
BoolNot = 12

Boolean NOT.

Examples:

not x  # boolean NOT
BoolAnd class-attribute instance-attribute ¤
BoolAnd = 13

Boolean AND.

Examples:

x and y  # boolean AND
BoolOr class-attribute instance-attribute ¤
BoolOr = 14

Boolean OR.

Examples:

x or y  # boolean OR
Conditional class-attribute instance-attribute ¤
Conditional = 15

Conditional expression: if - else expression.

Examples:

x if condition else y
Lambda class-attribute instance-attribute ¤
Lambda = 16

Lambda expression.

Examples:

lambda x, y: x + y
NamedExpr class-attribute instance-attribute ¤
NamedExpr = 17

Inline assignment expression.

Examples:

x := y

ExprType ¤

Bases: IntEnum

Expression type in Synt.

Source code in synt/expr/expr.py
class ExprType(IntEnum):
    r"""Expression type in Synt."""

    Atom = -1
    """Any expression type.

    This type is Reserved for internal use."""
    Unknown = -2
    """Unknown expression type.

    This type is Reserved for internal use."""

    Identifier = 0
    """[`IdentifierExpr`][synt.tokens.ident.IdentifierExpr]"""
    Wrapped = 1
    """[`Wrapped`][synt.expr.wrapped.Wrapped]."""
    KeyValuePair = 1
    """[`KVPair`][synt.tokens.kv_pair.KVPair]."""
    UnaryOp = 2
    """[`unary_op.UnaryOp`][synt.expr.unary_op.UnaryOp]."""
    BinaryOp = 3
    """[`binary_op.BinaryOp`][synt.expr.binary_op.BinaryOp]."""
    List = 4
    """[`ListDisplay`][synt.expr.list.ListDisplay]."""
    Dict = 5
    """[`DictDisplay`][synt.expr.dict.DictDisplay]."""
    Set = 6
    """[`SetDisplay`][synt.expr.set.SetDisplay]."""
    Tuple = 7
    """[`Tuple`][synt.expr.tuple.Tuple]."""
    Closure = 8
    """[`Closure`][synt.expr.closure.Closure]."""
    Condition = 9
    """[`Condition`][synt.expr.condition.Condition]."""
    NamedExpr = 10
    """[`NamedExpr`][synt.expr.named_expr.NamedExpr]."""
    Comprehension = 11
    """[`Comprehension`][synt.expr.comprehension.Comprehension]."""
    FormatString = 12
    """[`FormatString`][synt.expr.fstring.FormatString]"""
    Subscript = 13
    """[`subscript.Subscript`][synt.expr.subscript.Subscript]"""
    Attribute = 14
    """[`attribute.Attribute`][synt.expr.attribute.Attribute]"""
    Call = 15
    """[`call.Call`][synt.expr.call.Call]"""
    Literal = 16
    """[`tokens.lit.Literal`][synt.tokens.lit.Literal]"""
    Empty = 17
    """[`Empty`][synt.expr.empty.Empty]"""
Atom class-attribute instance-attribute ¤
Atom = -1

Any expression type.

This type is Reserved for internal use.

Unknown class-attribute instance-attribute ¤
Unknown = -2

Unknown expression type.

This type is Reserved for internal use.

Identifier class-attribute instance-attribute ¤
Identifier = 0
Wrapped class-attribute instance-attribute ¤
Wrapped = 1
KeyValuePair class-attribute instance-attribute ¤
KeyValuePair = 1
UnaryOp class-attribute instance-attribute ¤
UnaryOp = 2

unary_op.UnaryOp.

BinaryOp class-attribute instance-attribute ¤
BinaryOp = 3

binary_op.BinaryOp.

List class-attribute instance-attribute ¤
List = 4
Dict class-attribute instance-attribute ¤
Dict = 5
Set class-attribute instance-attribute ¤
Set = 6
Tuple class-attribute instance-attribute ¤
Tuple = 7
Closure class-attribute instance-attribute ¤
Closure = 8
Condition class-attribute instance-attribute ¤
Condition = 9
NamedExpr class-attribute instance-attribute ¤
NamedExpr = 10
Comprehension class-attribute instance-attribute ¤
Comprehension = 11
FormatString class-attribute instance-attribute ¤
FormatString = 12
Subscript class-attribute instance-attribute ¤
Subscript = 13

subscript.Subscript

Attribute class-attribute instance-attribute ¤
Attribute = 14

attribute.Attribute

Call class-attribute instance-attribute ¤
Call = 15

call.Call

Literal class-attribute instance-attribute ¤
Literal = 16

tokens.lit.Literal

Empty class-attribute instance-attribute ¤
Empty = 17

IntoExpression ¤

Bases: IntoCode

Abstract class for those that can be converted into an Expression.

Source code in synt/expr/expr.py
class IntoExpression(code.IntoCode, metaclass=ABCMeta):
    r"""Abstract class for those that can be converted into an
    [`Expression`][synt.expr.expr.Expression]."""

    @abstractmethod
    def into_expression(self) -> Expression:
        """Convert the object into an expression."""

    def expr(self) -> Expression:
        """Convert the object into an expression.

        This is a convenience method that calls `into_expression()` and returns the result.
        """
        return self.into_expression()

    def into_code(self) -> str:
        """Convert the object into a code string.

        This is a convenience method that calls `into_expression()` and calls `into_code` on the result.
        """
        return self.into_expression().into_code()
into_expression abstractmethod ¤
into_expression() -> Expression

Convert the object into an expression.

Source code in synt/expr/expr.py
@abstractmethod
def into_expression(self) -> Expression:
    """Convert the object into an expression."""
expr ¤
expr() -> Expression

Convert the object into an expression.

This is a convenience method that calls into_expression() and returns the result.

Source code in synt/expr/expr.py
def expr(self) -> Expression:
    """Convert the object into an expression.

    This is a convenience method that calls `into_expression()` and returns the result.
    """
    return self.into_expression()
into_code ¤
into_code() -> str

Convert the object into a code string.

This is a convenience method that calls into_expression() and calls into_code on the result.

Source code in synt/expr/expr.py
def into_code(self) -> str:
    """Convert the object into a code string.

    This is a convenience method that calls `into_expression()` and calls `into_code` on the result.
    """
    return self.into_expression().into_code()

Expression ¤

Bases: IntoExpression, IntoCode

Base class for any expression in Python.

Source code in synt/expr/expr.py
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
class Expression(IntoExpression, code.IntoCode, metaclass=ABCMeta):
    r"""Base class for any expression in Python."""

    @property
    @abstractmethod
    def precedence(self) -> ExprPrecedence:
        """The expression's precedence."""

    @property
    @abstractmethod
    def expr_type(self) -> ExprType:
        """The expression's type."""

    @abstractmethod
    def into_code(self) -> str:
        """Convert the expression into Python code.

        **No Formatting!**
        """

    def into_expression(self) -> Expression:
        """An `Expression` can always be converted into an `Expression`."""
        return self

    def ensure_identifier(self) -> Identifier:
        """Ensure that the expression is an identifier and returns it.

        Raises:
            ValueError: If the expression is not an identifier.
        """
        if type_check.is_ident(self):
            return self.ident
        else:
            raise ValueError("Expression is not an identifier")

    # alias for binary operation

    # bin op > plain method

    def add(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Add operation.

        Examples:
            ```python
            e = litint(1).add(id_("foo")) # alias ... + ...
            assert e.into_code() == "1 + foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Add, self, other)

    def sub(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Subtract operation.

        Examples:
            ```python
            e = litint(1).sub(id_("foo")) # alias ... - ...
            assert e.into_code() == "1 - foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Sub, self, other)

    def mul(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Multiply operation.

        Examples:
            ```python
            e = litint(1).mul(id_("foo")) # alias ... * ...
            assert e.into_code() == "1 * foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Mul, self, other)

    def div(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Divide operation.

        Examples:
            ```python
            e = litint(1).div(id_("foo")) # alias ... / ...
            assert e.into_code() == "1 / foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Div, self, other)

    def truediv(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`div`][synt.expr.expr.Expression.div]."""
        return self.div(other)

    def floor_div(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Floor divide operation.

        Examples:
            ```python
            e = litint(1).floor_div(id_("foo")) # alias ... // ...
            assert e.into_code() == "1 // foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.FloorDiv, self, other)

    def mod(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Modulus operation.

        Examples:
            ```python
            e = litint(1).mod(id_("foo")) # alias ... % ...
            assert e.into_code() == "1 % foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Mod, self, other)

    def pow(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Exponentiation operation.

        Examples:
            ```python
            e = litint(1).pow(id_("foo")) # alias ... ** ...
            assert e.into_code() == "1 ** foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Pow, self, other)

    def at(self, other: IntoExpression) -> binary_op.BinaryOp:
        """At(matrix multiplication) operation.

        Examples:
            ```python
            e = litint(1).at(id_("foo")) # alias ... @ ...
            assert e.into_code() == "1 @ foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.At, self, other)

    def matmul(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`at`][synt.expr.expr.Expression.matmul]."""
        return self.at(other)

    def lshift(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Left shift operation.

        Examples:
            ```python
            e = litint(1).lshift(id_("foo")) # alias ... << ...
            assert e.into_code() == "1 << foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.LShift, self, other)

    def rshift(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Right shift operation.

        Examples:
            ```python
            e = litint(1).rshift(id_("foo")) # alias ... >> ...
            assert e.into_code() == "1 >> foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.RShift, self, other)

    def lt(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Less than operation.

        Examples:
            ```python
            e = litint(1).lt(id_("foo")) # alias ... < ...
            assert e.into_code() == "1 < foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Less, self, other)

    def le(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Less than or equal to operation.

        Examples:
            ```python
            e = litint(1).le(id_("foo")) # alias ... <= ...
            assert e.into_code() == "1 <= foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.LessEqual, self, other)

    def gt(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Greater than operation.

        Examples:
            ```python
            e = litint(1).gt(id_("foo")) # alias ... > ...
            assert e.into_code() == "1 > foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Greater, self, other)

    def ge(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Greater than or equal to operation.

        Examples:
            ```python
            e = litint(1).ge(id_("foo")) # alias ... >= ...
            assert e.into_code() == "1 >= foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.GreaterEqual, self, other)

    def eq(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Equal to operation.

        Examples:
            ```python
            e = litint(1).eq(id_("foo")) # alias ... == ...
            assert e.into_code() == "1 == foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Equal, self, other)

    def ne(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Not equal to operation.

        Examples:
            ```python
            e = litint(1).ne(id_("foo")) # alias ... != ...
            assert e.into_code() == "1 != foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.NotEqual, self, other)

    def in_(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Membership test operation.

        Examples:
            ```python
            e = litint(1).in_(id_("foo")) # builtin check, no alias
            assert e.into_code() == "1 in foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.In, self, other)

    def not_in(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Negative membership test operation.

        Examples:
            ```python
            e = litint(1).not_in(id_("foo")) # builtin check, no alias
            assert e.into_code() == "1 not in foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.NotIn, self, other)

    def is_(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Identity test operation.

        Examples:
            ```python
            e = litint(1).is_(id_("foo")) # builtin check, no alias
            assert e.into_code() == "1 is foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Is, self, other)

    def is_not(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Negative identity test operation.

        Examples:
            ```python
            e = litint(1).is_not(id_("foo")) # builtin check, no alias
            assert e.into_code() == "1 is not foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.IsNot, self, other)

    def bool_and(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Boolean AND operation.

        Examples:
            ```python
            e = litint(1).bool_and(id_("foo")) # builtin operation, no alias
            assert e.into_code() == "1 and foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.BoolAnd, self, other)

    def bool_or(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Boolean OR operation.

        Examples:
            ```python
            e = litint(1).bool_or(id_("foo")) # builtin operation, no alias
            assert e.into_code() == "1 or foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.BoolOr, self, other)

    def bit_and(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Bitwise AND operation.

        Examples:
            ```python
            e = litint(1).bit_and(id_("foo")) # alias ... & ...
            assert e.into_code() == "1 & foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.BitAnd, self, other)

    def bit_or(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Bitwise OR operation.

        Examples:
            ```python
            e = litint(1).bit_or(id_("foo")) # alias ... | ...
            assert e.into_code() == "1 | foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.BitOr, self, other)

    def bit_xor(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Bitwise XOR operation.

        Examples:
            ```python
            e = litint(1).bit_xor(id_("foo")) # alias ... ^ ...
            assert e.into_code() == "1 ^ foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.BitXor, self, other)

    # bin op > magic method

    def __lt__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`lt`][synt.expr.expr.Expression.lt]."""
        return self.lt(other)

    def __le__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`le`][synt.expr.expr.Expression.le]."""
        return self.le(other)

    def __gt__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`gt`][synt.expr.expr.Expression.gt]."""
        return self.gt(other)

    def __ge__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`ge`][synt.expr.expr.Expression.ge]."""
        return self.ge(other)

    def __eq__(self, other: IntoExpression) -> binary_op.BinaryOp:  # type:ignore[override]
        """Alias [`eq`][synt.expr.expr.Expression.eq]."""
        return self.eq(other)

    def __ne__(self, other: IntoExpression) -> binary_op.BinaryOp:  # type:ignore[override]
        """Alias [`ne`][synt.expr.expr.Expression.ne]."""
        return self.ne(other)

    def __lshift__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`lshift`][synt.expr.expr.Expression.lshift]."""
        return self.lshift(other)

    def __rshift__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`rshift`][synt.expr.expr.Expression.rshift]."""
        return self.rshift(other)

    def __and__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`bit_and`][synt.expr.expr.Expression.bit_and]."""
        return self.bit_and(other)

    def __or__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`bit_or`][synt.expr.expr.Expression.bit_or]."""
        return self.bit_or(other)

    def __xor__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`bit_xor`][synt.expr.expr.Expression.bit_xor]."""
        return self.bit_xor(other)

    def __add__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`add`][synt.expr.expr.Expression.add]."""
        return self.add(other)

    def __sub__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`sub`][synt.expr.expr.Expression.sub]."""
        return self.sub(other)

    def __mul__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`mul`][synt.expr.expr.Expression.mul]."""
        return self.mul(other)

    def __truediv__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`div`][synt.expr.expr.Expression.div]."""
        return self.div(other)

    def __floordiv__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`floor_div`][synt.expr.expr.Expression.floor_div]."""
        return self.floor_div(other)

    def __mod__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`mod`][synt.expr.expr.Expression.mod]."""
        return self.mod(other)

    def __matmul__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`at`][synt.expr.expr.Expression.at]."""
        return self.at(other)

    # alias for unary operation

    # unary op > plain method

    def positive(self) -> unary_op.UnaryOp:
        """Positive operation, alias [`positive` function][synt.expr.unary_op.positive]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Positive, self)

    def negative(self) -> unary_op.UnaryOp:
        """Negative operation, alias [`negative` function][synt.expr.unary_op.negative]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Neg, self)

    def neg(self) -> unary_op.UnaryOp:
        """Alias [`negative`][synt.expr.expr.Expression.negative]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Neg, self)

    def not_(self) -> unary_op.UnaryOp:
        """Boolean NOT operation, alias [`not_` function][synt.expr.unary_op.not_]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.BoolNot, self)

    def bool_not(self) -> unary_op.UnaryOp:
        """Alias [`not_`][synt.expr.expr.Expression.not_]."""
        return self.not_()

    def invert(self) -> unary_op.UnaryOp:
        """Bitwise NOT operation, alias [`invert` function][synt.expr.unary_op.invert]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.BitNot, self)

    def bit_not(self) -> unary_op.UnaryOp:
        """Alias [`invert`][synt.expr.expr.Expression.invert]."""
        return self.invert()

    def await_(self) -> unary_op.UnaryOp:
        """Await operation, alias [`await_` function][synt.expr.unary_op.await_]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Await, self)

    def awaited(self) -> unary_op.UnaryOp:
        """Alias [`await_`][synt.expr.expr.Expression.await_]"""
        return self.await_()

    def unpack(self) -> unary_op.UnaryOp:
        """Sequence unpacking operation, Alias [`unpack` function][synt.expr.unary_op.unpack]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Starred, self)

    def starred(self) -> unary_op.UnaryOp:
        """Alias [`unpack`][synt.expr.expr.Expression.unpack]."""
        return self.unpack()

    def unpack_seq(self) -> unary_op.UnaryOp:
        """Alias [`unpack`][synt.expr.expr.Expression.unpack]."""
        return self.unpack()

    def unpack_kv(self) -> unary_op.UnaryOp:
        """K-V pair unpacking operation, Alias [`unpack_kv` function][synt.expr.unary_op.unpack_kv]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.DoubleStarred, self)

    def double_starred(self) -> unary_op.UnaryOp:
        """Alias [`unpack_kv`][synt.expr.expr.Expression.unpack_kv]."""
        return self.unpack_kv()

    def unpack_dict(self) -> unary_op.UnaryOp:
        """Alias [`unpack_kv`][synt.expr.expr.Expression.unpack_kv]."""
        return self.unpack_kv()

    def yield_(self) -> unary_op.UnaryOp:
        """Yield operation, alias [`yield_` function][synt.expr.unary_op.yield_]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Yield, self)

    def yield_from(self) -> unary_op.UnaryOp:
        """Yield from operation, alias [`yield_from` function][synt.expr.unary_op.yield_from]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.YieldFrom, self)

    # unary op > magic method

    def __neg__(self) -> unary_op.UnaryOp:
        """Alias [`neg`][synt.expr.expr.Expression.neg]."""
        return self.neg()

    def __not__(self) -> unary_op.UnaryOp:
        """Alias [`not_`][synt.expr.expr.Expression.not_]."""
        return self.not_()

    def __invert__(self) -> unary_op.UnaryOp:
        """Alias [`invert`][synt.expr.expr.Expression.invert]."""
        return self.invert()

    # alias for named value

    def named(self, expr: IntoExpression) -> named_expr.NamedExpr:
        """Assign the expression to `self`.

        Args:
            expr: The expression to assign.

        Raises:
            ValueError: If `self` is not an identifier.

        Examples:
            ```python
            named_expr = id_('a').expr().named(litint(1))
            assert named_expr.into_code() == "a := 1"
            ```
        """
        return named_expr.NamedExpr(self.ensure_identifier(), expr)

    def named_as(self, target: Identifier) -> named_expr.NamedExpr:
        """Assign self to the target.

        Args:
            target: The target identifier.

        Examples:
            ```python
            named_as_expr = (litint(1) + litint(2)).named_as(id_('a')).is_(TRUE)
            assert named_as_expr.into_code() == "(a := 1 + 2) is True"
            ```
        """
        return named_expr.NamedExpr(target, self)

    # alias for attribute

    def attr(self, attr: str) -> attribute.Attribute:
        """attribute.Attribute getting operation.

        Args:
            attr: The attribute name.

        Examples:
            ```python
            attr_expr = id_('a').expr().attr('b').expr().call(litint(1), litint(2))
            assert attr_expr.into_code() == "a.b(1, 2)"
            ```
        """
        return attribute.Attribute(self, attr)

    # alias for call

    def call(
        self,
        *args: IntoExpression | tuple[Identifier, IntoExpression],
        **kwargs: IntoExpression,
    ) -> call.Call:
        """Calling a function or object.

        Args:
            *args: Positional arguments.
            **kwargs: Keyword arguments.

        Raises:
            ValueError: If any argument is not [`IntoExpression`][synt.expr.expr.IntoExpression].

        Examples:
            ```python
            call_expr = id_('a').expr().call(litint(1), litint(2)).call(kw=litint(3))
            assert call_expr.into_code() == "a(1, 2)(kw=3)"
            ```
            With dynamic keyword arguments:
            ```python
            call_expr = id_('a').expr().call(kwarg(id_('b'), litint(42)))
            assert call_expr.into_code() == "a(b=42)"
            ```
        """
        from synt.tokens.ident import Identifier

        kwarg: list[call.Keyword] = []
        arg: list[IntoExpression] = []
        for a in args:
            if isinstance(a, tuple):
                kwarg.append(call.Keyword(a[0], a[1]))
                continue
            if type_check.is_into_expr(a):
                arg.append(a)
                continue
            raise ValueError(f"Invalid argument: {a}")

        for k, v in kwargs.items():
            kwarg.append(call.Keyword(Identifier(k), v))

        return call.Call(self, arg, kwarg)

    # alias for comprehension

    def for_(self, *target: Identifier) -> comprehension.ComprehensionNodeBuilder:
        """Initialize a new comprehension.

        Args:
            target: The target of the iteration.

        Examples:
            ```python
            # `comp_expr` here only implements `IntoExpression` and `IntoCode`
            # because it's still a non-finished builder
            comp_expr = list_comp(id_('x').expr()
                .for_(id_('x')).in_(id_('range').expr().call(litint(5)))
                .if_((id_('x').expr() % litint(2)) == litint(0)))
            assert comp_expr.into_code() == "[x for x in range(5) if x % 2 == 0]"
            ```
        """
        return comprehension.ComprehensionBuilder.init(self, list(target), False)

    def async_for(self, *target: Identifier) -> comprehension.ComprehensionNodeBuilder:
        """Initialize a new async comprehension.

        Args:
            target: The iterator expression of the comprehension.

        Examples:
            ```python
            # `comp_expr` here only implements `IntoExpression` and `IntoCode`
            # because it's still a non-finished builder
            comp_expr = list_comp(id_('x').expr()
                .async_for(id_('x')).in_(id_('range').expr().call(litint(5)))
                .if_((id_('x').expr() % litint(2)) == litint(0)))
            assert comp_expr.into_code() == "[x async for x in range(5) if x % 2 == 0]"
            ```
        """
        return comprehension.ComprehensionBuilder.init(self, list(target), True)

    # alias for condition

    def if_(self, cond: IntoExpression) -> condition.ConditionBuilder:
        """Initialize a new condition expression.

        Args:
            cond: The condition expression.

        Examples:
            ```python
            cond_expr = id_('a').expr().if_(id_('b').expr() > litint(0)).else_(litstr('foo'))
            assert cond_expr.into_code() == "a if b > 0 else 'foo'"
            ```
        """
        return condition.ConditionBuilder(cond, self)

    # alias for subscript

    # subscript > plain method

    def subscribe(
        self, *slices: subscript.Slice | IntoExpression
    ) -> subscript.Subscript:
        """Subscribe to the expression.

        Args:
            slices: The slice expressions.

        Examples:
            ```python
            subscript_expr = id_('a').expr().subscribe(id_('b').expr(), slice_(litint(2), litint(3)))
            # also alias: ...[...]
            assert subscript_expr.into_code() == "a[b, 2:3]"
            ```
        """
        return subscript.Subscript(self, list(slices))

    # subscript > magic method

    def __getitem__(
        self,
        items: tuple[subscript.Slice | IntoExpression, ...]
        | subscript.Slice
        | IntoExpression,
    ) -> subscript.Subscript:
        """Alias [`subscribe`][synt.expr.expr.Expression.subscribe]."""
        if isinstance(items, tuple):
            return self.subscribe(*items)
        else:
            return self.subscribe(items)

    # wrap

    def wrap(self) -> expr_wrapped.Wrapped:
        """Wrap `self` in a pair of parentheses, alias [`Wrapped`][synt.expr.wrapped.Wrapped]."""
        return expr_wrapped.Wrapped(self)

    def wrapped(self) -> expr_wrapped.Wrapped:
        """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
        return self.wrap()

    def par(self) -> expr_wrapped.Wrapped:
        """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
        return self.wrap()

    def atom(self) -> expr_wrapped.Wrapped:
        """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
        return self.wrap()

    # statement constructors

    # assignment

    def assign(self, value: IntoExpression) -> stmt_assign.Assignment:
        """Create a new assignment statement, take `self` as the target.

        Args:
            value: The value to assign.
        """
        return stmt_assign.Assignment(self).assign(value)

    def assign_to(self, target: IntoExpression) -> stmt_assign.Assignment:
        """Create a new assignment statement, take `self` as the value.

        Args:
            target: The value to be assigned.
        """
        return stmt_assign.Assignment(target.into_expression()).assign(self)

    def type(self, ty: IntoExpression) -> stmt_assign.Assignment:
        """Create a new typed assignment statement, take `self` as the target.

        Args:
            ty: The type of the target.
        """
        return stmt_assign.Assignment(self).type(ty)

    def ty(self, ty: IntoExpression) -> stmt_assign.Assignment:
        """Alias [`type`][synt.expr.expr.Expression.type]."""
        return self.type(ty)

    def stmt(self) -> Statement:
        """Convert the expression into a statement."""
        from synt.stmt.expression import stmt

        return stmt(self)

    def as_(self, target: Identifier) -> Alias:
        """Convert the expression into an alias.

        Args:
            target: The target identifier.
        """
        from synt.expr.alias import Alias

        return Alias(self, target)
precedence abstractmethod property ¤
precedence: ExprPrecedence

The expression's precedence.

expr_type abstractmethod property ¤
expr_type: ExprType

The expression's type.

into_code abstractmethod ¤
into_code() -> str

Convert the expression into Python code.

No Formatting!

Source code in synt/expr/expr.py
@abstractmethod
def into_code(self) -> str:
    """Convert the expression into Python code.

    **No Formatting!**
    """
into_expression ¤
into_expression() -> Expression

An Expression can always be converted into an Expression.

Source code in synt/expr/expr.py
def into_expression(self) -> Expression:
    """An `Expression` can always be converted into an `Expression`."""
    return self
ensure_identifier ¤
ensure_identifier() -> Identifier

Ensure that the expression is an identifier and returns it.

Raises:

Type Description
ValueError

If the expression is not an identifier.

Source code in synt/expr/expr.py
def ensure_identifier(self) -> Identifier:
    """Ensure that the expression is an identifier and returns it.

    Raises:
        ValueError: If the expression is not an identifier.
    """
    if type_check.is_ident(self):
        return self.ident
    else:
        raise ValueError("Expression is not an identifier")
add ¤
add(other: IntoExpression) -> BinaryOp

Add operation.

Examples:

e = litint(1).add(id_("foo")) # alias ... + ...
assert e.into_code() == "1 + foo"
Source code in synt/expr/expr.py
def add(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Add operation.

    Examples:
        ```python
        e = litint(1).add(id_("foo")) # alias ... + ...
        assert e.into_code() == "1 + foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Add, self, other)
sub ¤
sub(other: IntoExpression) -> BinaryOp

Subtract operation.

Examples:

e = litint(1).sub(id_("foo")) # alias ... - ...
assert e.into_code() == "1 - foo"
Source code in synt/expr/expr.py
def sub(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Subtract operation.

    Examples:
        ```python
        e = litint(1).sub(id_("foo")) # alias ... - ...
        assert e.into_code() == "1 - foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Sub, self, other)
mul ¤
mul(other: IntoExpression) -> BinaryOp

Multiply operation.

Examples:

e = litint(1).mul(id_("foo")) # alias ... * ...
assert e.into_code() == "1 * foo"
Source code in synt/expr/expr.py
def mul(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Multiply operation.

    Examples:
        ```python
        e = litint(1).mul(id_("foo")) # alias ... * ...
        assert e.into_code() == "1 * foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Mul, self, other)
div ¤
div(other: IntoExpression) -> BinaryOp

Divide operation.

Examples:

e = litint(1).div(id_("foo")) # alias ... / ...
assert e.into_code() == "1 / foo"
Source code in synt/expr/expr.py
def div(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Divide operation.

    Examples:
        ```python
        e = litint(1).div(id_("foo")) # alias ... / ...
        assert e.into_code() == "1 / foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Div, self, other)
truediv ¤
truediv(other: IntoExpression) -> BinaryOp

Alias div.

Source code in synt/expr/expr.py
def truediv(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`div`][synt.expr.expr.Expression.div]."""
    return self.div(other)
floor_div ¤
floor_div(other: IntoExpression) -> BinaryOp

Floor divide operation.

Examples:

e = litint(1).floor_div(id_("foo")) # alias ... // ...
assert e.into_code() == "1 // foo"
Source code in synt/expr/expr.py
def floor_div(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Floor divide operation.

    Examples:
        ```python
        e = litint(1).floor_div(id_("foo")) # alias ... // ...
        assert e.into_code() == "1 // foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.FloorDiv, self, other)
mod ¤
mod(other: IntoExpression) -> BinaryOp

Modulus operation.

Examples:

e = litint(1).mod(id_("foo")) # alias ... % ...
assert e.into_code() == "1 % foo"
Source code in synt/expr/expr.py
def mod(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Modulus operation.

    Examples:
        ```python
        e = litint(1).mod(id_("foo")) # alias ... % ...
        assert e.into_code() == "1 % foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Mod, self, other)
pow ¤
pow(other: IntoExpression) -> BinaryOp

Exponentiation operation.

Examples:

e = litint(1).pow(id_("foo")) # alias ... ** ...
assert e.into_code() == "1 ** foo"
Source code in synt/expr/expr.py
def pow(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Exponentiation operation.

    Examples:
        ```python
        e = litint(1).pow(id_("foo")) # alias ... ** ...
        assert e.into_code() == "1 ** foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Pow, self, other)
at ¤
at(other: IntoExpression) -> BinaryOp

At(matrix multiplication) operation.

Examples:

e = litint(1).at(id_("foo")) # alias ... @ ...
assert e.into_code() == "1 @ foo"
Source code in synt/expr/expr.py
def at(self, other: IntoExpression) -> binary_op.BinaryOp:
    """At(matrix multiplication) operation.

    Examples:
        ```python
        e = litint(1).at(id_("foo")) # alias ... @ ...
        assert e.into_code() == "1 @ foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.At, self, other)
matmul ¤
matmul(other: IntoExpression) -> BinaryOp

Alias at.

Source code in synt/expr/expr.py
def matmul(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`at`][synt.expr.expr.Expression.matmul]."""
    return self.at(other)
lshift ¤
lshift(other: IntoExpression) -> BinaryOp

Left shift operation.

Examples:

e = litint(1).lshift(id_("foo")) # alias ... << ...
assert e.into_code() == "1 << foo"
Source code in synt/expr/expr.py
def lshift(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Left shift operation.

    Examples:
        ```python
        e = litint(1).lshift(id_("foo")) # alias ... << ...
        assert e.into_code() == "1 << foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.LShift, self, other)
rshift ¤
rshift(other: IntoExpression) -> BinaryOp

Right shift operation.

Examples:

e = litint(1).rshift(id_("foo")) # alias ... >> ...
assert e.into_code() == "1 >> foo"
Source code in synt/expr/expr.py
def rshift(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Right shift operation.

    Examples:
        ```python
        e = litint(1).rshift(id_("foo")) # alias ... >> ...
        assert e.into_code() == "1 >> foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.RShift, self, other)
lt ¤
lt(other: IntoExpression) -> BinaryOp

Less than operation.

Examples:

e = litint(1).lt(id_("foo")) # alias ... < ...
assert e.into_code() == "1 < foo"
Source code in synt/expr/expr.py
def lt(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Less than operation.

    Examples:
        ```python
        e = litint(1).lt(id_("foo")) # alias ... < ...
        assert e.into_code() == "1 < foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Less, self, other)
le ¤
le(other: IntoExpression) -> BinaryOp

Less than or equal to operation.

Examples:

e = litint(1).le(id_("foo")) # alias ... <= ...
assert e.into_code() == "1 <= foo"
Source code in synt/expr/expr.py
def le(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Less than or equal to operation.

    Examples:
        ```python
        e = litint(1).le(id_("foo")) # alias ... <= ...
        assert e.into_code() == "1 <= foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.LessEqual, self, other)
gt ¤
gt(other: IntoExpression) -> BinaryOp

Greater than operation.

Examples:

e = litint(1).gt(id_("foo")) # alias ... > ...
assert e.into_code() == "1 > foo"
Source code in synt/expr/expr.py
def gt(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Greater than operation.

    Examples:
        ```python
        e = litint(1).gt(id_("foo")) # alias ... > ...
        assert e.into_code() == "1 > foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Greater, self, other)
ge ¤
ge(other: IntoExpression) -> BinaryOp

Greater than or equal to operation.

Examples:

e = litint(1).ge(id_("foo")) # alias ... >= ...
assert e.into_code() == "1 >= foo"
Source code in synt/expr/expr.py
def ge(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Greater than or equal to operation.

    Examples:
        ```python
        e = litint(1).ge(id_("foo")) # alias ... >= ...
        assert e.into_code() == "1 >= foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.GreaterEqual, self, other)
eq ¤
eq(other: IntoExpression) -> BinaryOp

Equal to operation.

Examples:

e = litint(1).eq(id_("foo")) # alias ... == ...
assert e.into_code() == "1 == foo"
Source code in synt/expr/expr.py
def eq(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Equal to operation.

    Examples:
        ```python
        e = litint(1).eq(id_("foo")) # alias ... == ...
        assert e.into_code() == "1 == foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Equal, self, other)
ne ¤
ne(other: IntoExpression) -> BinaryOp

Not equal to operation.

Examples:

e = litint(1).ne(id_("foo")) # alias ... != ...
assert e.into_code() == "1 != foo"
Source code in synt/expr/expr.py
def ne(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Not equal to operation.

    Examples:
        ```python
        e = litint(1).ne(id_("foo")) # alias ... != ...
        assert e.into_code() == "1 != foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.NotEqual, self, other)
in_ ¤
in_(other: IntoExpression) -> BinaryOp

Membership test operation.

Examples:

e = litint(1).in_(id_("foo")) # builtin check, no alias
assert e.into_code() == "1 in foo"
Source code in synt/expr/expr.py
def in_(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Membership test operation.

    Examples:
        ```python
        e = litint(1).in_(id_("foo")) # builtin check, no alias
        assert e.into_code() == "1 in foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.In, self, other)
not_in ¤
not_in(other: IntoExpression) -> BinaryOp

Negative membership test operation.

Examples:

e = litint(1).not_in(id_("foo")) # builtin check, no alias
assert e.into_code() == "1 not in foo"
Source code in synt/expr/expr.py
def not_in(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Negative membership test operation.

    Examples:
        ```python
        e = litint(1).not_in(id_("foo")) # builtin check, no alias
        assert e.into_code() == "1 not in foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.NotIn, self, other)
is_ ¤
is_(other: IntoExpression) -> BinaryOp

Identity test operation.

Examples:

e = litint(1).is_(id_("foo")) # builtin check, no alias
assert e.into_code() == "1 is foo"
Source code in synt/expr/expr.py
def is_(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Identity test operation.

    Examples:
        ```python
        e = litint(1).is_(id_("foo")) # builtin check, no alias
        assert e.into_code() == "1 is foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Is, self, other)
is_not ¤
is_not(other: IntoExpression) -> BinaryOp

Negative identity test operation.

Examples:

e = litint(1).is_not(id_("foo")) # builtin check, no alias
assert e.into_code() == "1 is not foo"
Source code in synt/expr/expr.py
def is_not(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Negative identity test operation.

    Examples:
        ```python
        e = litint(1).is_not(id_("foo")) # builtin check, no alias
        assert e.into_code() == "1 is not foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.IsNot, self, other)
bool_and ¤
bool_and(other: IntoExpression) -> BinaryOp

Boolean AND operation.

Examples:

e = litint(1).bool_and(id_("foo")) # builtin operation, no alias
assert e.into_code() == "1 and foo"
Source code in synt/expr/expr.py
def bool_and(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Boolean AND operation.

    Examples:
        ```python
        e = litint(1).bool_and(id_("foo")) # builtin operation, no alias
        assert e.into_code() == "1 and foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.BoolAnd, self, other)
bool_or ¤
bool_or(other: IntoExpression) -> BinaryOp

Boolean OR operation.

Examples:

e = litint(1).bool_or(id_("foo")) # builtin operation, no alias
assert e.into_code() == "1 or foo"
Source code in synt/expr/expr.py
def bool_or(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Boolean OR operation.

    Examples:
        ```python
        e = litint(1).bool_or(id_("foo")) # builtin operation, no alias
        assert e.into_code() == "1 or foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.BoolOr, self, other)
bit_and ¤
bit_and(other: IntoExpression) -> BinaryOp

Bitwise AND operation.

Examples:

e = litint(1).bit_and(id_("foo")) # alias ... & ...
assert e.into_code() == "1 & foo"
Source code in synt/expr/expr.py
def bit_and(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Bitwise AND operation.

    Examples:
        ```python
        e = litint(1).bit_and(id_("foo")) # alias ... & ...
        assert e.into_code() == "1 & foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.BitAnd, self, other)
bit_or ¤
bit_or(other: IntoExpression) -> BinaryOp

Bitwise OR operation.

Examples:

e = litint(1).bit_or(id_("foo")) # alias ... | ...
assert e.into_code() == "1 | foo"
Source code in synt/expr/expr.py
def bit_or(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Bitwise OR operation.

    Examples:
        ```python
        e = litint(1).bit_or(id_("foo")) # alias ... | ...
        assert e.into_code() == "1 | foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.BitOr, self, other)
bit_xor ¤
bit_xor(other: IntoExpression) -> BinaryOp

Bitwise XOR operation.

Examples:

e = litint(1).bit_xor(id_("foo")) # alias ... ^ ...
assert e.into_code() == "1 ^ foo"
Source code in synt/expr/expr.py
def bit_xor(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Bitwise XOR operation.

    Examples:
        ```python
        e = litint(1).bit_xor(id_("foo")) # alias ... ^ ...
        assert e.into_code() == "1 ^ foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.BitXor, self, other)
__lt__ ¤
__lt__(other: IntoExpression) -> BinaryOp

Alias lt.

Source code in synt/expr/expr.py
def __lt__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`lt`][synt.expr.expr.Expression.lt]."""
    return self.lt(other)
__le__ ¤
__le__(other: IntoExpression) -> BinaryOp

Alias le.

Source code in synt/expr/expr.py
def __le__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`le`][synt.expr.expr.Expression.le]."""
    return self.le(other)
__gt__ ¤
__gt__(other: IntoExpression) -> BinaryOp

Alias gt.

Source code in synt/expr/expr.py
def __gt__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`gt`][synt.expr.expr.Expression.gt]."""
    return self.gt(other)
__ge__ ¤
__ge__(other: IntoExpression) -> BinaryOp

Alias ge.

Source code in synt/expr/expr.py
def __ge__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`ge`][synt.expr.expr.Expression.ge]."""
    return self.ge(other)
__eq__ ¤
__eq__(other: IntoExpression) -> BinaryOp

Alias eq.

Source code in synt/expr/expr.py
def __eq__(self, other: IntoExpression) -> binary_op.BinaryOp:  # type:ignore[override]
    """Alias [`eq`][synt.expr.expr.Expression.eq]."""
    return self.eq(other)
__ne__ ¤
__ne__(other: IntoExpression) -> BinaryOp

Alias ne.

Source code in synt/expr/expr.py
def __ne__(self, other: IntoExpression) -> binary_op.BinaryOp:  # type:ignore[override]
    """Alias [`ne`][synt.expr.expr.Expression.ne]."""
    return self.ne(other)
__lshift__ ¤
__lshift__(other: IntoExpression) -> BinaryOp

Alias lshift.

Source code in synt/expr/expr.py
def __lshift__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`lshift`][synt.expr.expr.Expression.lshift]."""
    return self.lshift(other)
__rshift__ ¤
__rshift__(other: IntoExpression) -> BinaryOp

Alias rshift.

Source code in synt/expr/expr.py
def __rshift__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`rshift`][synt.expr.expr.Expression.rshift]."""
    return self.rshift(other)
__and__ ¤
__and__(other: IntoExpression) -> BinaryOp

Alias bit_and.

Source code in synt/expr/expr.py
def __and__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`bit_and`][synt.expr.expr.Expression.bit_and]."""
    return self.bit_and(other)
__or__ ¤
__or__(other: IntoExpression) -> BinaryOp

Alias bit_or.

Source code in synt/expr/expr.py
def __or__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`bit_or`][synt.expr.expr.Expression.bit_or]."""
    return self.bit_or(other)
__xor__ ¤
__xor__(other: IntoExpression) -> BinaryOp

Alias bit_xor.

Source code in synt/expr/expr.py
def __xor__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`bit_xor`][synt.expr.expr.Expression.bit_xor]."""
    return self.bit_xor(other)
__add__ ¤
__add__(other: IntoExpression) -> BinaryOp

Alias add.

Source code in synt/expr/expr.py
def __add__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`add`][synt.expr.expr.Expression.add]."""
    return self.add(other)
__sub__ ¤
__sub__(other: IntoExpression) -> BinaryOp

Alias sub.

Source code in synt/expr/expr.py
def __sub__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`sub`][synt.expr.expr.Expression.sub]."""
    return self.sub(other)
__mul__ ¤
__mul__(other: IntoExpression) -> BinaryOp

Alias mul.

Source code in synt/expr/expr.py
def __mul__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`mul`][synt.expr.expr.Expression.mul]."""
    return self.mul(other)
__truediv__ ¤
__truediv__(other: IntoExpression) -> BinaryOp

Alias div.

Source code in synt/expr/expr.py
def __truediv__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`div`][synt.expr.expr.Expression.div]."""
    return self.div(other)
__floordiv__ ¤
__floordiv__(other: IntoExpression) -> BinaryOp

Alias floor_div.

Source code in synt/expr/expr.py
def __floordiv__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`floor_div`][synt.expr.expr.Expression.floor_div]."""
    return self.floor_div(other)
__mod__ ¤
__mod__(other: IntoExpression) -> BinaryOp

Alias mod.

Source code in synt/expr/expr.py
def __mod__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`mod`][synt.expr.expr.Expression.mod]."""
    return self.mod(other)
__matmul__ ¤
__matmul__(other: IntoExpression) -> BinaryOp

Alias at.

Source code in synt/expr/expr.py
def __matmul__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`at`][synt.expr.expr.Expression.at]."""
    return self.at(other)
positive ¤
positive() -> UnaryOp

Positive operation, alias positive function.

Source code in synt/expr/expr.py
def positive(self) -> unary_op.UnaryOp:
    """Positive operation, alias [`positive` function][synt.expr.unary_op.positive]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Positive, self)
negative ¤
negative() -> UnaryOp

Negative operation, alias negative function.

Source code in synt/expr/expr.py
def negative(self) -> unary_op.UnaryOp:
    """Negative operation, alias [`negative` function][synt.expr.unary_op.negative]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Neg, self)
neg ¤
neg() -> UnaryOp

Alias negative.

Source code in synt/expr/expr.py
def neg(self) -> unary_op.UnaryOp:
    """Alias [`negative`][synt.expr.expr.Expression.negative]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Neg, self)
not_ ¤
not_() -> UnaryOp

Boolean NOT operation, alias not_ function.

Source code in synt/expr/expr.py
def not_(self) -> unary_op.UnaryOp:
    """Boolean NOT operation, alias [`not_` function][synt.expr.unary_op.not_]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.BoolNot, self)
bool_not ¤
bool_not() -> UnaryOp

Alias not_.

Source code in synt/expr/expr.py
def bool_not(self) -> unary_op.UnaryOp:
    """Alias [`not_`][synt.expr.expr.Expression.not_]."""
    return self.not_()
invert ¤
invert() -> UnaryOp

Bitwise NOT operation, alias invert function.

Source code in synt/expr/expr.py
def invert(self) -> unary_op.UnaryOp:
    """Bitwise NOT operation, alias [`invert` function][synt.expr.unary_op.invert]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.BitNot, self)
bit_not ¤
bit_not() -> UnaryOp

Alias invert.

Source code in synt/expr/expr.py
def bit_not(self) -> unary_op.UnaryOp:
    """Alias [`invert`][synt.expr.expr.Expression.invert]."""
    return self.invert()
await_ ¤
await_() -> UnaryOp

Await operation, alias await_ function.

Source code in synt/expr/expr.py
def await_(self) -> unary_op.UnaryOp:
    """Await operation, alias [`await_` function][synt.expr.unary_op.await_]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Await, self)
awaited ¤
awaited() -> UnaryOp

Alias await_

Source code in synt/expr/expr.py
def awaited(self) -> unary_op.UnaryOp:
    """Alias [`await_`][synt.expr.expr.Expression.await_]"""
    return self.await_()
unpack ¤
unpack() -> UnaryOp

Sequence unpacking operation, Alias unpack function.

Source code in synt/expr/expr.py
def unpack(self) -> unary_op.UnaryOp:
    """Sequence unpacking operation, Alias [`unpack` function][synt.expr.unary_op.unpack]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Starred, self)
starred ¤
starred() -> UnaryOp

Alias unpack.

Source code in synt/expr/expr.py
def starred(self) -> unary_op.UnaryOp:
    """Alias [`unpack`][synt.expr.expr.Expression.unpack]."""
    return self.unpack()
unpack_seq ¤
unpack_seq() -> UnaryOp

Alias unpack.

Source code in synt/expr/expr.py
def unpack_seq(self) -> unary_op.UnaryOp:
    """Alias [`unpack`][synt.expr.expr.Expression.unpack]."""
    return self.unpack()
unpack_kv ¤
unpack_kv() -> UnaryOp

K-V pair unpacking operation, Alias unpack_kv function.

Source code in synt/expr/expr.py
def unpack_kv(self) -> unary_op.UnaryOp:
    """K-V pair unpacking operation, Alias [`unpack_kv` function][synt.expr.unary_op.unpack_kv]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.DoubleStarred, self)
double_starred ¤
double_starred() -> UnaryOp

Alias unpack_kv.

Source code in synt/expr/expr.py
def double_starred(self) -> unary_op.UnaryOp:
    """Alias [`unpack_kv`][synt.expr.expr.Expression.unpack_kv]."""
    return self.unpack_kv()
unpack_dict ¤
unpack_dict() -> UnaryOp

Alias unpack_kv.

Source code in synt/expr/expr.py
def unpack_dict(self) -> unary_op.UnaryOp:
    """Alias [`unpack_kv`][synt.expr.expr.Expression.unpack_kv]."""
    return self.unpack_kv()
yield_ ¤
yield_() -> UnaryOp

Yield operation, alias yield_ function.

Source code in synt/expr/expr.py
def yield_(self) -> unary_op.UnaryOp:
    """Yield operation, alias [`yield_` function][synt.expr.unary_op.yield_]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Yield, self)
yield_from ¤
yield_from() -> UnaryOp

Yield from operation, alias yield_from function.

Source code in synt/expr/expr.py
def yield_from(self) -> unary_op.UnaryOp:
    """Yield from operation, alias [`yield_from` function][synt.expr.unary_op.yield_from]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.YieldFrom, self)
__neg__ ¤
__neg__() -> UnaryOp

Alias neg.

Source code in synt/expr/expr.py
def __neg__(self) -> unary_op.UnaryOp:
    """Alias [`neg`][synt.expr.expr.Expression.neg]."""
    return self.neg()
__not__ ¤
__not__() -> UnaryOp

Alias not_.

Source code in synt/expr/expr.py
def __not__(self) -> unary_op.UnaryOp:
    """Alias [`not_`][synt.expr.expr.Expression.not_]."""
    return self.not_()
__invert__ ¤
__invert__() -> UnaryOp

Alias invert.

Source code in synt/expr/expr.py
def __invert__(self) -> unary_op.UnaryOp:
    """Alias [`invert`][synt.expr.expr.Expression.invert]."""
    return self.invert()
named ¤
named(expr: IntoExpression) -> NamedExpr

Assign the expression to self.

Parameters:

Name Type Description Default
expr IntoExpression

The expression to assign.

required

Raises:

Type Description
ValueError

If self is not an identifier.

Examples:

named_expr = id_('a').expr().named(litint(1))
assert named_expr.into_code() == "a := 1"
Source code in synt/expr/expr.py
def named(self, expr: IntoExpression) -> named_expr.NamedExpr:
    """Assign the expression to `self`.

    Args:
        expr: The expression to assign.

    Raises:
        ValueError: If `self` is not an identifier.

    Examples:
        ```python
        named_expr = id_('a').expr().named(litint(1))
        assert named_expr.into_code() == "a := 1"
        ```
    """
    return named_expr.NamedExpr(self.ensure_identifier(), expr)
named_as ¤
named_as(target: Identifier) -> NamedExpr

Assign self to the target.

Parameters:

Name Type Description Default
target Identifier

The target identifier.

required

Examples:

named_as_expr = (litint(1) + litint(2)).named_as(id_('a')).is_(TRUE)
assert named_as_expr.into_code() == "(a := 1 + 2) is True"
Source code in synt/expr/expr.py
def named_as(self, target: Identifier) -> named_expr.NamedExpr:
    """Assign self to the target.

    Args:
        target: The target identifier.

    Examples:
        ```python
        named_as_expr = (litint(1) + litint(2)).named_as(id_('a')).is_(TRUE)
        assert named_as_expr.into_code() == "(a := 1 + 2) is True"
        ```
    """
    return named_expr.NamedExpr(target, self)
attr ¤
attr(attr: str) -> Attribute

attribute.Attribute getting operation.

Parameters:

Name Type Description Default
attr str

The attribute name.

required

Examples:

attr_expr = id_('a').expr().attr('b').expr().call(litint(1), litint(2))
assert attr_expr.into_code() == "a.b(1, 2)"
Source code in synt/expr/expr.py
def attr(self, attr: str) -> attribute.Attribute:
    """attribute.Attribute getting operation.

    Args:
        attr: The attribute name.

    Examples:
        ```python
        attr_expr = id_('a').expr().attr('b').expr().call(litint(1), litint(2))
        assert attr_expr.into_code() == "a.b(1, 2)"
        ```
    """
    return attribute.Attribute(self, attr)
call ¤
1
2
3
4
5
call(
    *args: IntoExpression
    | tuple[Identifier, IntoExpression],
    **kwargs: IntoExpression
) -> Call

Calling a function or object.

Parameters:

Name Type Description Default
*args IntoExpression | tuple[Identifier, IntoExpression]

Positional arguments.

()
**kwargs IntoExpression

Keyword arguments.

{}

Raises:

Type Description
ValueError

If any argument is not IntoExpression.

Examples:

call_expr = id_('a').expr().call(litint(1), litint(2)).call(kw=litint(3))
assert call_expr.into_code() == "a(1, 2)(kw=3)"
With dynamic keyword arguments:
call_expr = id_('a').expr().call(kwarg(id_('b'), litint(42)))
assert call_expr.into_code() == "a(b=42)"

Source code in synt/expr/expr.py
def call(
    self,
    *args: IntoExpression | tuple[Identifier, IntoExpression],
    **kwargs: IntoExpression,
) -> call.Call:
    """Calling a function or object.

    Args:
        *args: Positional arguments.
        **kwargs: Keyword arguments.

    Raises:
        ValueError: If any argument is not [`IntoExpression`][synt.expr.expr.IntoExpression].

    Examples:
        ```python
        call_expr = id_('a').expr().call(litint(1), litint(2)).call(kw=litint(3))
        assert call_expr.into_code() == "a(1, 2)(kw=3)"
        ```
        With dynamic keyword arguments:
        ```python
        call_expr = id_('a').expr().call(kwarg(id_('b'), litint(42)))
        assert call_expr.into_code() == "a(b=42)"
        ```
    """
    from synt.tokens.ident import Identifier

    kwarg: list[call.Keyword] = []
    arg: list[IntoExpression] = []
    for a in args:
        if isinstance(a, tuple):
            kwarg.append(call.Keyword(a[0], a[1]))
            continue
        if type_check.is_into_expr(a):
            arg.append(a)
            continue
        raise ValueError(f"Invalid argument: {a}")

    for k, v in kwargs.items():
        kwarg.append(call.Keyword(Identifier(k), v))

    return call.Call(self, arg, kwarg)
for_ ¤

Initialize a new comprehension.

Parameters:

Name Type Description Default
target Identifier

The target of the iteration.

()

Examples:

1
2
3
4
5
6
# `comp_expr` here only implements `IntoExpression` and `IntoCode`
# because it's still a non-finished builder
comp_expr = list_comp(id_('x').expr()
    .for_(id_('x')).in_(id_('range').expr().call(litint(5)))
    .if_((id_('x').expr() % litint(2)) == litint(0)))
assert comp_expr.into_code() == "[x for x in range(5) if x % 2 == 0]"
Source code in synt/expr/expr.py
def for_(self, *target: Identifier) -> comprehension.ComprehensionNodeBuilder:
    """Initialize a new comprehension.

    Args:
        target: The target of the iteration.

    Examples:
        ```python
        # `comp_expr` here only implements `IntoExpression` and `IntoCode`
        # because it's still a non-finished builder
        comp_expr = list_comp(id_('x').expr()
            .for_(id_('x')).in_(id_('range').expr().call(litint(5)))
            .if_((id_('x').expr() % litint(2)) == litint(0)))
        assert comp_expr.into_code() == "[x for x in range(5) if x % 2 == 0]"
        ```
    """
    return comprehension.ComprehensionBuilder.init(self, list(target), False)
async_for ¤
async_for(*target: Identifier) -> ComprehensionNodeBuilder

Initialize a new async comprehension.

Parameters:

Name Type Description Default
target Identifier

The iterator expression of the comprehension.

()

Examples:

1
2
3
4
5
6
# `comp_expr` here only implements `IntoExpression` and `IntoCode`
# because it's still a non-finished builder
comp_expr = list_comp(id_('x').expr()
    .async_for(id_('x')).in_(id_('range').expr().call(litint(5)))
    .if_((id_('x').expr() % litint(2)) == litint(0)))
assert comp_expr.into_code() == "[x async for x in range(5) if x % 2 == 0]"
Source code in synt/expr/expr.py
def async_for(self, *target: Identifier) -> comprehension.ComprehensionNodeBuilder:
    """Initialize a new async comprehension.

    Args:
        target: The iterator expression of the comprehension.

    Examples:
        ```python
        # `comp_expr` here only implements `IntoExpression` and `IntoCode`
        # because it's still a non-finished builder
        comp_expr = list_comp(id_('x').expr()
            .async_for(id_('x')).in_(id_('range').expr().call(litint(5)))
            .if_((id_('x').expr() % litint(2)) == litint(0)))
        assert comp_expr.into_code() == "[x async for x in range(5) if x % 2 == 0]"
        ```
    """
    return comprehension.ComprehensionBuilder.init(self, list(target), True)
if_ ¤

Initialize a new condition expression.

Parameters:

Name Type Description Default
cond IntoExpression

The condition expression.

required

Examples:

cond_expr = id_('a').expr().if_(id_('b').expr() > litint(0)).else_(litstr('foo'))
assert cond_expr.into_code() == "a if b > 0 else 'foo'"
Source code in synt/expr/expr.py
def if_(self, cond: IntoExpression) -> condition.ConditionBuilder:
    """Initialize a new condition expression.

    Args:
        cond: The condition expression.

    Examples:
        ```python
        cond_expr = id_('a').expr().if_(id_('b').expr() > litint(0)).else_(litstr('foo'))
        assert cond_expr.into_code() == "a if b > 0 else 'foo'"
        ```
    """
    return condition.ConditionBuilder(cond, self)
subscribe ¤
subscribe(*slices: Slice | IntoExpression) -> Subscript

Subscribe to the expression.

Parameters:

Name Type Description Default
slices Slice | IntoExpression

The slice expressions.

()

Examples:

1
2
3
subscript_expr = id_('a').expr().subscribe(id_('b').expr(), slice_(litint(2), litint(3)))
# also alias: ...[...]
assert subscript_expr.into_code() == "a[b, 2:3]"
Source code in synt/expr/expr.py
def subscribe(
    self, *slices: subscript.Slice | IntoExpression
) -> subscript.Subscript:
    """Subscribe to the expression.

    Args:
        slices: The slice expressions.

    Examples:
        ```python
        subscript_expr = id_('a').expr().subscribe(id_('b').expr(), slice_(litint(2), litint(3)))
        # also alias: ...[...]
        assert subscript_expr.into_code() == "a[b, 2:3]"
        ```
    """
    return subscript.Subscript(self, list(slices))
__getitem__ ¤
1
2
3
4
5
6
7
__getitem__(
    items: (
        tuple[Slice | IntoExpression, ...]
        | Slice
        | IntoExpression
    )
) -> Subscript

Alias subscribe.

Source code in synt/expr/expr.py
def __getitem__(
    self,
    items: tuple[subscript.Slice | IntoExpression, ...]
    | subscript.Slice
    | IntoExpression,
) -> subscript.Subscript:
    """Alias [`subscribe`][synt.expr.expr.Expression.subscribe]."""
    if isinstance(items, tuple):
        return self.subscribe(*items)
    else:
        return self.subscribe(items)
wrap ¤
wrap() -> Wrapped

Wrap self in a pair of parentheses, alias Wrapped.

Source code in synt/expr/expr.py
def wrap(self) -> expr_wrapped.Wrapped:
    """Wrap `self` in a pair of parentheses, alias [`Wrapped`][synt.expr.wrapped.Wrapped]."""
    return expr_wrapped.Wrapped(self)
wrapped ¤
wrapped() -> Wrapped

Alias wrap.

Source code in synt/expr/expr.py
def wrapped(self) -> expr_wrapped.Wrapped:
    """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
    return self.wrap()
par ¤
par() -> Wrapped

Alias wrap.

Source code in synt/expr/expr.py
def par(self) -> expr_wrapped.Wrapped:
    """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
    return self.wrap()
atom ¤
atom() -> Wrapped

Alias wrap.

Source code in synt/expr/expr.py
def atom(self) -> expr_wrapped.Wrapped:
    """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
    return self.wrap()
assign ¤
assign(value: IntoExpression) -> Assignment

Create a new assignment statement, take self as the target.

Parameters:

Name Type Description Default
value IntoExpression

The value to assign.

required
Source code in synt/expr/expr.py
def assign(self, value: IntoExpression) -> stmt_assign.Assignment:
    """Create a new assignment statement, take `self` as the target.

    Args:
        value: The value to assign.
    """
    return stmt_assign.Assignment(self).assign(value)
assign_to ¤
assign_to(target: IntoExpression) -> Assignment

Create a new assignment statement, take self as the value.

Parameters:

Name Type Description Default
target IntoExpression

The value to be assigned.

required
Source code in synt/expr/expr.py
def assign_to(self, target: IntoExpression) -> stmt_assign.Assignment:
    """Create a new assignment statement, take `self` as the value.

    Args:
        target: The value to be assigned.
    """
    return stmt_assign.Assignment(target.into_expression()).assign(self)
type ¤

Create a new typed assignment statement, take self as the target.

Parameters:

Name Type Description Default
ty IntoExpression

The type of the target.

required
Source code in synt/expr/expr.py
def type(self, ty: IntoExpression) -> stmt_assign.Assignment:
    """Create a new typed assignment statement, take `self` as the target.

    Args:
        ty: The type of the target.
    """
    return stmt_assign.Assignment(self).type(ty)
ty ¤

Alias type.

Source code in synt/expr/expr.py
def ty(self, ty: IntoExpression) -> stmt_assign.Assignment:
    """Alias [`type`][synt.expr.expr.Expression.type]."""
    return self.type(ty)
stmt ¤
stmt() -> Statement

Convert the expression into a statement.

Source code in synt/expr/expr.py
def stmt(self) -> Statement:
    """Convert the expression into a statement."""
    from synt.stmt.expression import stmt

    return stmt(self)
as_ ¤
as_(target: Identifier) -> Alias

Convert the expression into an alias.

Parameters:

Name Type Description Default
target Identifier

The target identifier.

required
Source code in synt/expr/expr.py
def as_(self, target: Identifier) -> Alias:
    """Convert the expression into an alias.

    Args:
        target: The target identifier.
    """
    from synt.expr.alias import Alias

    return Alias(self, target)

fstring ¤

fstring module-attribute ¤

fstring = FormatString

Alias FormatString.

fnode module-attribute ¤

fnode = FormatNode

Alias FormatNode.

FormatString ¤

Bases: Expression

Format string, aka f-string.

Examples:

string = fstring("sin(1) = ", fnode(id_("sin").expr().call(litint(1))))
assert string.into_code() == 'f"sin(1) = {sin(1)}"'
References

expr.ExprType.FormatString.

Source code in synt/expr/fstring.py
class FormatString(expr.Expression):
    r"""Format string, aka f-string.

    Examples:
        ```python
        string = fstring("sin(1) = ", fnode(id_("sin").expr().call(litint(1))))
        assert string.into_code() == 'f"sin(1) = {sin(1)}"'
        ```

    References:
        [expr.ExprType.FormatString][synt.expr.expr.ExprType.FormatString].
    """

    nodes: list[FormatNode | str]
    """Formatting nodes."""

    precedence = expr.ExprPrecedence.Atom
    expr_type = expr.ExprType.FormatString

    def __init__(self, *nodes: FormatNode | str):
        """Initialize a new format string expression.

        Args:
            nodes: Formatting nodes.
        """
        self.nodes = list(nodes)

    def into_code(self) -> str:
        string = ""
        for item in self.nodes:
            if isinstance(item, str):
                string += item
            else:
                string += item.into_code()
        return f'f"{string}"'
precedence class-attribute instance-attribute ¤
precedence = Atom
expr_type class-attribute instance-attribute ¤
expr_type = FormatString
nodes instance-attribute ¤
nodes: list[FormatNode | str] = list(nodes)

Formatting nodes.

__init__ ¤
__init__(*nodes: FormatNode | str)

Initialize a new format string expression.

Parameters:

Name Type Description Default
nodes FormatNode | str

Formatting nodes.

()
Source code in synt/expr/fstring.py
def __init__(self, *nodes: FormatNode | str):
    """Initialize a new format string expression.

    Args:
        nodes: Formatting nodes.
    """
    self.nodes = list(nodes)
into_code ¤
into_code() -> str
Source code in synt/expr/fstring.py
def into_code(self) -> str:
    string = ""
    for item in self.nodes:
        if isinstance(item, str):
            string += item
        else:
            string += item.into_code()
    return f'f"{string}"'

FormatConversionType ¤

Bases: IntEnum

Format conversion type.

References

FormattedValue.

Source code in synt/expr/fstring.py
class FormatConversionType(IntEnum):
    r"""Format conversion type.

    References:
        [`FormattedValue`](https://docs.python.org/3/library/ast.html#ast.FormattedValue).
    """

    No = -1
    """No formatting."""
    Ascii = 97
    """Ascii representation, aka `!a`."""
    Repr = 114
    """`__repr__` representation, aka `!r`."""
    Str = 115
    """`__str__` representation, aka `!s`."""

    @staticmethod
    def from_str(s: str) -> FormatConversionType:
        """Parse a conversion string.

        | text          | result                       |
        | ------------- | ---------------------------- |
        | `""`, `"!"`   | `FormatConversionType.No`    |
        | `"a"`, `"!a"` | `FormatConversionType.Ascii` |
        | `"r"`, `"!r"` | `FormatConversionType.Repr`  |
        | `"s"`, `"!s"` | `FormatConversionType.Str`   |

        Args:
            s: Conversion string.

        Raises:
            ValueError: If the conversion string is invalid (valid forms are the texts listed above).
        """
        s = s.removeprefix("!")
        match s:
            case "":
                return FormatConversionType.No
            case "a":
                return FormatConversionType.Ascii
            case "r":
                return FormatConversionType.Repr
            case "s":
                return FormatConversionType.Str
            case r:
                raise ValueError(f"Invalid conversion string: {r}")

    def into_str(self) -> str:
        """Converts the conversion type into a string.

        Raises
            ValueError: If the conversion type is not recognized.
        """
        match self:
            case FormatConversionType.No:
                return ""
            case FormatConversionType.Ascii:
                return "!a"
            case FormatConversionType.Repr:
                return "!r"
            case FormatConversionType.Str:
                return "!s"
            case _ as conversion_type:
                raise ValueError(f"Unrecognized conversion type: {conversion_type}")
No class-attribute instance-attribute ¤
No = -1

No formatting.

Ascii class-attribute instance-attribute ¤
Ascii = 97

Ascii representation, aka !a.

Repr class-attribute instance-attribute ¤
Repr = 114

__repr__ representation, aka !r.

Str class-attribute instance-attribute ¤
Str = 115

__str__ representation, aka !s.

from_str staticmethod ¤
from_str(s: str) -> FormatConversionType

Parse a conversion string.

text result
"", "!" FormatConversionType.No
"a", "!a" FormatConversionType.Ascii
"r", "!r" FormatConversionType.Repr
"s", "!s" FormatConversionType.Str

Parameters:

Name Type Description Default
s str

Conversion string.

required

Raises:

Type Description
ValueError

If the conversion string is invalid (valid forms are the texts listed above).

Source code in synt/expr/fstring.py
@staticmethod
def from_str(s: str) -> FormatConversionType:
    """Parse a conversion string.

    | text          | result                       |
    | ------------- | ---------------------------- |
    | `""`, `"!"`   | `FormatConversionType.No`    |
    | `"a"`, `"!a"` | `FormatConversionType.Ascii` |
    | `"r"`, `"!r"` | `FormatConversionType.Repr`  |
    | `"s"`, `"!s"` | `FormatConversionType.Str`   |

    Args:
        s: Conversion string.

    Raises:
        ValueError: If the conversion string is invalid (valid forms are the texts listed above).
    """
    s = s.removeprefix("!")
    match s:
        case "":
            return FormatConversionType.No
        case "a":
            return FormatConversionType.Ascii
        case "r":
            return FormatConversionType.Repr
        case "s":
            return FormatConversionType.Str
        case r:
            raise ValueError(f"Invalid conversion string: {r}")
into_str ¤
into_str() -> str

Converts the conversion type into a string.

Raises ValueError: If the conversion type is not recognized.

Source code in synt/expr/fstring.py
def into_str(self) -> str:
    """Converts the conversion type into a string.

    Raises
        ValueError: If the conversion type is not recognized.
    """
    match self:
        case FormatConversionType.No:
            return ""
        case FormatConversionType.Ascii:
            return "!a"
        case FormatConversionType.Repr:
            return "!r"
        case FormatConversionType.Str:
            return "!s"
        case _ as conversion_type:
            raise ValueError(f"Unrecognized conversion type: {conversion_type}")

FormatNode ¤

Bases: IntoCode

Format node used in FormatString.

Examples:

node = fnode(id_("sin").expr().call(litint(1)), ".2")
assert node.into_code() == "{sin(1):.2}"
Source code in synt/expr/fstring.py
class FormatNode(code.IntoCode):
    r"""Format node used in [`FormatString`][synt.expr.fstring.FormatString].

    Examples:
        ```python
        node = fnode(id_("sin").expr().call(litint(1)), ".2")
        assert node.into_code() == "{sin(1):.2}"
        ```
    """

    value: expr.Expression
    """expr.Expression to be joint with other nodes."""
    format_spec: str | None
    """The formatting of the value.

    Notes:
        Different from Python's behavior, Synt directly use `str` as the type of `format_spec`,
        instead of wrapping it in a `JointStr(Constant(string))`.
    """
    conversion: FormatConversionType
    """The conversion of the expression, e.g. `__str__`, `__repr__`, ..."""

    def __init__(
        self,
        value: expr.IntoExpression,
        format_spec: str | None = None,
        conversion: FormatConversionType | str = FormatConversionType.No,
    ):
        """Initialize a format node.

        Args:
            value: expr.Expression to be joint with other nodes.
            format_spec: The formatting of the value.
            conversion: The conversion of the expression.
        """
        self.value = value.into_expression()
        self.format_spec = format_spec
        self.conversion = (
            FormatConversionType.from_str(conversion)
            if isinstance(conversion, str)
            else conversion
        )

    def into_code(self) -> str:
        fmt_spec = f":{self.format_spec}" if self.format_spec else ""
        return f"{{{self.value.into_code()}{self.conversion.into_str()}{fmt_spec}}}"
value instance-attribute ¤
value: Expression = into_expression()

expr.Expression to be joint with other nodes.

format_spec instance-attribute ¤
format_spec: str | None = format_spec

The formatting of the value.

Notes

Different from Python's behavior, Synt directly use str as the type of format_spec, instead of wrapping it in a JointStr(Constant(string)).

conversion instance-attribute ¤

The conversion of the expression, e.g. __str__, __repr__, ...

__init__ ¤
1
2
3
4
5
6
7
__init__(
    value: IntoExpression,
    format_spec: str | None = None,
    conversion: (
        FormatConversionType | str
    ) = FormatConversionType.No,
)

Initialize a format node.

Parameters:

Name Type Description Default
value IntoExpression

expr.Expression to be joint with other nodes.

required
format_spec str | None

The formatting of the value.

None
conversion FormatConversionType | str

The conversion of the expression.

No
Source code in synt/expr/fstring.py
def __init__(
    self,
    value: expr.IntoExpression,
    format_spec: str | None = None,
    conversion: FormatConversionType | str = FormatConversionType.No,
):
    """Initialize a format node.

    Args:
        value: expr.Expression to be joint with other nodes.
        format_spec: The formatting of the value.
        conversion: The conversion of the expression.
    """
    self.value = value.into_expression()
    self.format_spec = format_spec
    self.conversion = (
        FormatConversionType.from_str(conversion)
        if isinstance(conversion, str)
        else conversion
    )
into_code ¤
into_code() -> str
Source code in synt/expr/fstring.py
def into_code(self) -> str:
    fmt_spec = f":{self.format_spec}" if self.format_spec else ""
    return f"{{{self.value.into_code()}{self.conversion.into_str()}{fmt_spec}}}"

list ¤

list_ module-attribute ¤

list_ = ListVerbatim

Alias ListVerbatim.

Notes

list is a built-in type in Python, so it's renamed to list_ with a suffix.

list_comp module-attribute ¤

list_comp = ListComprehension

ListDisplay ¤

Bases: Expression

Literal list expression.

References

list display.

Source code in synt/expr/list.py
class ListDisplay(expr.Expression, metaclass=ABCMeta):
    r"""Literal list expression.

    References:
        [list display](https://docs.python.org/3/reference/expressions.html#list-displays).
    """

    precedence = expr.ExprPrecedence.Atom
    expr_type = expr.ExprType.List
precedence class-attribute instance-attribute ¤
precedence = Atom
expr_type class-attribute instance-attribute ¤
expr_type = List

ListVerbatim ¤

Bases: ListDisplay

Verbatim list expression, aka starred-list.

Examples:

l = list_(litstr("a"), id_("b"))
assert l.into_code() == "['a', b]"
References

starred-list.

Source code in synt/expr/list.py
class ListVerbatim(ListDisplay):
    r"""Verbatim list expression, aka `starred-list`.

    Examples:
        ```python
        l = list_(litstr("a"), id_("b"))
        assert l.into_code() == "['a', b]"
        ```

    References:
        [`starred-list`](https://docs.python.org/3/reference/expressions.html#grammar-token-python-grammar-starred_list).
    """

    items: list[expr.Expression]
    """list items."""

    def __init__(self, *items: expr.IntoExpression):
        """Initialize a new verbatim list expression.

        Args:
            items: list items.
        """
        self.items = [x.into_expression() for x in items]

    def into_code(self) -> str:
        item_text = ", ".join(x.into_code() for x in self.items)
        return f"[{item_text}]"
items instance-attribute ¤
1
2
3
items: list[Expression] = [
    into_expression() for x in items
]

list items.

__init__ ¤
__init__(*items: IntoExpression)

Initialize a new verbatim list expression.

Parameters:

Name Type Description Default
items IntoExpression

list items.

()
Source code in synt/expr/list.py
def __init__(self, *items: expr.IntoExpression):
    """Initialize a new verbatim list expression.

    Args:
        items: list items.
    """
    self.items = [x.into_expression() for x in items]
into_code ¤
into_code() -> str
Source code in synt/expr/list.py
def into_code(self) -> str:
    item_text = ", ".join(x.into_code() for x in self.items)
    return f"[{item_text}]"

ListComprehension ¤

Bases: ListDisplay

list comprehension expression.

Examples:

l = list_comp(id_("x").expr().for_(id_("x")).in_(id_("range").expr().call(litint(5))))
assert l.into_code() == "[x for x in range(5)]"
References

comprehension.

Source code in synt/expr/list.py
class ListComprehension(ListDisplay):
    r"""list comprehension expression.

    Examples:
        ```python
        l = list_comp(id_("x").expr().for_(id_("x")).in_(id_("range").expr().call(litint(5))))
        assert l.into_code() == "[x for x in range(5)]"
        ```

    References:
        [`comprehension`](https://docs.python.org/3/reference/
        expressions.html#grammar-tokens-python-grammar-comprehension).
    """

    comprehension: comp_expr.Comprehension
    """Internal comprehension expression."""

    def __init__(
        self,
        comprehension: comp_expr.Comprehension
        | comp_expr.ComprehensionBuilder
        | comp_expr.ComprehensionNodeBuilder,
    ):
        """Initialize a new list comprehension expression.

        Args:
            comprehension: Internal comprehension expression.

        Raises:
            ExpressionTypeException: Invalid list comprehension result type,
                typically a [`KVPair`][synt.tokens.kv_pair.KVPair].
        """
        if isinstance(comprehension, comp_expr.Comprehension):
            comp = comprehension
        elif isinstance(comprehension, comp_expr.ComprehensionBuilder):
            comp = comprehension.build()
        elif isinstance(comprehension, comp_expr.ComprehensionNodeBuilder):
            comp = comprehension.build_comp()
        else:
            raise ValueError(
                "Expect expression of type `Comprehension`, found `Unknown`."
            )

        if comp.elt.expr_type == expr.ExprType.KeyValuePair:
            raise ValueError("Expect expression of type `Atom`, found `KeyValuePair`.")
        self.comprehension = comp

    def into_code(self) -> str:
        return f"[{self.comprehension.into_code()}]"
comprehension instance-attribute ¤
comprehension: Comprehension = comp

Internal comprehension expression.

__init__ ¤
1
2
3
4
5
6
7
__init__(
    comprehension: (
        Comprehension
        | ComprehensionBuilder
        | ComprehensionNodeBuilder
    ),
)

Initialize a new list comprehension expression.

Parameters:

Name Type Description Default
comprehension Comprehension | ComprehensionBuilder | ComprehensionNodeBuilder

Internal comprehension expression.

required

Raises:

Type Description
ExpressionTypeException

Invalid list comprehension result type, typically a KVPair.

Source code in synt/expr/list.py
def __init__(
    self,
    comprehension: comp_expr.Comprehension
    | comp_expr.ComprehensionBuilder
    | comp_expr.ComprehensionNodeBuilder,
):
    """Initialize a new list comprehension expression.

    Args:
        comprehension: Internal comprehension expression.

    Raises:
        ExpressionTypeException: Invalid list comprehension result type,
            typically a [`KVPair`][synt.tokens.kv_pair.KVPair].
    """
    if isinstance(comprehension, comp_expr.Comprehension):
        comp = comprehension
    elif isinstance(comprehension, comp_expr.ComprehensionBuilder):
        comp = comprehension.build()
    elif isinstance(comprehension, comp_expr.ComprehensionNodeBuilder):
        comp = comprehension.build_comp()
    else:
        raise ValueError(
            "Expect expression of type `Comprehension`, found `Unknown`."
        )

    if comp.elt.expr_type == expr.ExprType.KeyValuePair:
        raise ValueError("Expect expression of type `Atom`, found `KeyValuePair`.")
    self.comprehension = comp
into_code ¤
into_code() -> str
Source code in synt/expr/list.py
def into_code(self) -> str:
    return f"[{self.comprehension.into_code()}]"

modpath ¤

path module-attribute ¤

path = ModPath

Alias ModPath.

ModPath ¤

Bases: IntoCode

Module path.

Examples:

1
2
3
4
5
6
7
8
p = path(id_('foo'))
assert p.into_code() == "foo"
p = path(id_('foo'), id_('bar'))
assert p.into_code() == "foo.bar"
p = path(id_('foo'), id_('bar'), depth=3)
assert p.into_code() == "...foo.bar"
p = path(id_('foo'), id_('bar')).dep(4)
assert p.into_code() == "....foo.bar"
Source code in synt/expr/modpath.py
class ModPath(IntoCode):
    r"""Module path.

    Examples:
        ```python
        p = path(id_('foo'))
        assert p.into_code() == "foo"
        p = path(id_('foo'), id_('bar'))
        assert p.into_code() == "foo.bar"
        p = path(id_('foo'), id_('bar'), depth=3)
        assert p.into_code() == "...foo.bar"
        p = path(id_('foo'), id_('bar')).dep(4)
        assert p.into_code() == "....foo.bar"
        ```
    """

    names: list[Identifier]
    """Names of the path."""
    depth: int
    """Relative depth of the path."""

    def __init__(self, *names: Identifier, depth: int = 0):
        """Initialize a new module path.

        Args:
            names: Names of the path.
            depth: Relative depth of the path.
        """
        self.names = list(names)
        self.depth = depth

    def dep(self, depth: int) -> Self:
        """Set the depth of the path.

        Args:
            depth: New depth of the path.
        """
        self.depth = depth
        return self

    def into_code(self) -> str:
        return "." * self.depth + ".".join(name.into_code() for name in self.names)

    def as_(self, asname: Identifier) -> Alias:
        """Alias the import path.

        Args:
            asname: Name of the alias.
        """
        from synt.expr.alias import Alias

        return Alias(self, asname)
names instance-attribute ¤

Names of the path.

depth instance-attribute ¤
depth: int = depth

Relative depth of the path.

__init__ ¤
__init__(*names: Identifier, depth: int = 0)

Initialize a new module path.

Parameters:

Name Type Description Default
names Identifier

Names of the path.

()
depth int

Relative depth of the path.

0
Source code in synt/expr/modpath.py
def __init__(self, *names: Identifier, depth: int = 0):
    """Initialize a new module path.

    Args:
        names: Names of the path.
        depth: Relative depth of the path.
    """
    self.names = list(names)
    self.depth = depth
dep ¤
dep(depth: int) -> Self

Set the depth of the path.

Parameters:

Name Type Description Default
depth int

New depth of the path.

required
Source code in synt/expr/modpath.py
def dep(self, depth: int) -> Self:
    """Set the depth of the path.

    Args:
        depth: New depth of the path.
    """
    self.depth = depth
    return self
into_code ¤
into_code() -> str
Source code in synt/expr/modpath.py
def into_code(self) -> str:
    return "." * self.depth + ".".join(name.into_code() for name in self.names)
as_ ¤
as_(asname: Identifier) -> Alias

Alias the import path.

Parameters:

Name Type Description Default
asname Identifier

Name of the alias.

required
Source code in synt/expr/modpath.py
def as_(self, asname: Identifier) -> Alias:
    """Alias the import path.

    Args:
        asname: Name of the alias.
    """
    from synt.expr.alias import Alias

    return Alias(self, asname)

relpath ¤

relpath(*names: Identifier) -> ModPath

Initialize a path relatively (depth = 1).

Parameters:

Name Type Description Default
names Identifier

Names of the path.

()

Examples:

r = relpath(id_("abc"))
assert r.into_code() == ".abc"
Source code in synt/expr/modpath.py
def relpath(*names: Identifier) -> ModPath:
    r"""Initialize a path relatively (`depth = 1`).

    Args:
        names: Names of the path.

    Examples:
        ```python
        r = relpath(id_("abc"))
        assert r.into_code() == ".abc"
        ```
    """
    return ModPath(*names, depth=1)

parentpath ¤

parentpath(*names: Identifier) -> ModPath

Initialize a path from its parent (depth = 2).

Parameters:

Name Type Description Default
names Identifier

Names of the path.

()

Examples:

r = parentpath(id_("abc"))
assert r.into_code() == "..abc"
Source code in synt/expr/modpath.py
def parentpath(*names: Identifier) -> ModPath:
    r"""Initialize a path from its parent (`depth = 2`).

    Args:
        names: Names of the path.

    Examples:
        ```python
        r = parentpath(id_("abc"))
        assert r.into_code() == "..abc"
        ```
    """
    return ModPath(*names, depth=2)

named_expr ¤

NamedExpr ¤

Bases: Expression

Inline assignment expression, aka :=.

References

expr.ExprPrecedence.NamedExpr.

Source code in synt/expr/named_expr.py
class NamedExpr(expr.Expression):
    r"""Inline assignment expression, aka `:=`.

    References:
        [expr.ExprPrecedence.NamedExpr][synt.expr.expr.ExprPrecedence.NamedExpr].
    """

    receiver: Identifier
    """The identifier to be assigned."""
    value: expr.Expression
    """The value to be assigned to the receiver."""
    precedence = expr.ExprPrecedence.NamedExpr
    expr_type = expr.ExprType.NamedExpr

    def __init__(self, receiver: Identifier, value: expr.IntoExpression):
        """Initialize a named expr expression.

        Args:
            receiver: The identifier to be assigned.
            value: The value to be assigned to the receiver.
        """
        self.receiver = receiver
        self.value = value.into_expression()

        if self.value.precedence > self.precedence:
            self.value = self.value.wrapped()

    def into_code(self) -> str:
        return f"{self.receiver.into_code()} := {self.value.into_code()}"
precedence class-attribute instance-attribute ¤
precedence = NamedExpr
expr_type class-attribute instance-attribute ¤
expr_type = NamedExpr
receiver instance-attribute ¤
receiver: Identifier = receiver

The identifier to be assigned.

value instance-attribute ¤
value: Expression = into_expression()

The value to be assigned to the receiver.

__init__ ¤
__init__(receiver: Identifier, value: IntoExpression)

Initialize a named expr expression.

Parameters:

Name Type Description Default
receiver Identifier

The identifier to be assigned.

required
value IntoExpression

The value to be assigned to the receiver.

required
Source code in synt/expr/named_expr.py
def __init__(self, receiver: Identifier, value: expr.IntoExpression):
    """Initialize a named expr expression.

    Args:
        receiver: The identifier to be assigned.
        value: The value to be assigned to the receiver.
    """
    self.receiver = receiver
    self.value = value.into_expression()

    if self.value.precedence > self.precedence:
        self.value = self.value.wrapped()
into_code ¤
into_code() -> str
Source code in synt/expr/named_expr.py
def into_code(self) -> str:
    return f"{self.receiver.into_code()} := {self.value.into_code()}"

set ¤

set_ module-attribute ¤

set_ = SetVerbatim

Alias SetVerbatim.

Notes

set is a built-in type in Python, so it's renamed to set_ with a suffix.

set_comp module-attribute ¤

set_comp = SetComprehension

SetDisplay ¤

Bases: Expression

Literal set expression.

References

Set display.

Source code in synt/expr/set.py
class SetDisplay(expr.Expression, metaclass=ABCMeta):
    r"""Literal set expression.

    References:
        [Set display](https://docs.python.org/3/reference/expressions.html#set-displays).
    """

    precedence = expr.ExprPrecedence.Atom
    expr_type = expr.ExprType.Set
precedence class-attribute instance-attribute ¤
precedence = Atom
expr_type class-attribute instance-attribute ¤
expr_type = Set

SetVerbatim ¤

Bases: SetDisplay

Verbatim set expression.

Examples:

s = set_(litint(1), id_("b"))
assert s.into_code() == "{1, b}"
Source code in synt/expr/set.py
class SetVerbatim(SetDisplay):
    r"""Verbatim set expression.

    Examples:
        ```python
        s = set_(litint(1), id_("b"))
        assert s.into_code() == "{1, b}"
        ```
    """

    items: list[expr.Expression]
    """Set items."""

    def __init__(self, *items: expr.IntoExpression):
        """Initialize a new verbatim set expression.

        Args:
            items: Set items.
        """
        self.items = [x.into_expression() for x in items]

    def into_code(self) -> str:
        item_text = ", ".join(x.into_code() for x in self.items)
        return f"{{{item_text}}}"
items instance-attribute ¤
1
2
3
items: list[Expression] = [
    into_expression() for x in items
]

Set items.

__init__ ¤
__init__(*items: IntoExpression)

Initialize a new verbatim set expression.

Parameters:

Name Type Description Default
items IntoExpression

Set items.

()
Source code in synt/expr/set.py
def __init__(self, *items: expr.IntoExpression):
    """Initialize a new verbatim set expression.

    Args:
        items: Set items.
    """
    self.items = [x.into_expression() for x in items]
into_code ¤
into_code() -> str
Source code in synt/expr/set.py
def into_code(self) -> str:
    item_text = ", ".join(x.into_code() for x in self.items)
    return f"{{{item_text}}}"

SetComprehension ¤

Bases: SetDisplay

Set comprehension expression.

Examples:

s = set_comp(id_("x").expr().for_(id_("x")).in_(id_("range").expr().call(litint(5))))
assert s.into_code() == "{x for x in range(5)}"
References

comprehension.

Source code in synt/expr/set.py
class SetComprehension(SetDisplay):
    r"""Set comprehension expression.

    Examples:
        ```python
        s = set_comp(id_("x").expr().for_(id_("x")).in_(id_("range").expr().call(litint(5))))
        assert s.into_code() == "{x for x in range(5)}"
        ```

    References:
        [`comprehension`](https://docs.python.org/3/reference/
        expressions.html#grammar-tokens-python-grammar-comprehension).
    """

    comprehension: comp_expr.Comprehension
    """Internal comprehension expression."""

    def __init__(
        self,
        comprehension: comp_expr.Comprehension
        | comp_expr.ComprehensionBuilder
        | comp_expr.ComprehensionNodeBuilder,
    ):
        """Initialize a new set comprehension expression.

        Args:
            comprehension: Internal comprehension expression.

        Raises:
            ExpressionTypeException: Invalid set comprehension result type,
                typically a [`KVPair`][synt.tokens.kv_pair.KVPair].
        """
        if isinstance(comprehension, comp_expr.Comprehension):
            comp = comprehension
        elif isinstance(comprehension, comp_expr.ComprehensionBuilder):
            comp = comprehension.build()
        elif isinstance(comprehension, comp_expr.ComprehensionNodeBuilder):
            comp = comprehension.build_comp()
        else:
            raise ValueError(
                "Expect expression of type `Comprehension`, found `Unknown`."
            )

        if comp.elt.expr_type == expr.ExprType.KeyValuePair:
            raise ValueError("Expect expression of type `Atom`, found `KeyValuePair`.")
        self.comprehension = comp

    def into_code(self) -> str:
        return f"{{{self.comprehension.into_code()}}}"
comprehension instance-attribute ¤
comprehension: Comprehension = comp

Internal comprehension expression.

__init__ ¤
1
2
3
4
5
6
7
__init__(
    comprehension: (
        Comprehension
        | ComprehensionBuilder
        | ComprehensionNodeBuilder
    ),
)

Initialize a new set comprehension expression.

Parameters:

Name Type Description Default
comprehension Comprehension | ComprehensionBuilder | ComprehensionNodeBuilder

Internal comprehension expression.

required

Raises:

Type Description
ExpressionTypeException

Invalid set comprehension result type, typically a KVPair.

Source code in synt/expr/set.py
def __init__(
    self,
    comprehension: comp_expr.Comprehension
    | comp_expr.ComprehensionBuilder
    | comp_expr.ComprehensionNodeBuilder,
):
    """Initialize a new set comprehension expression.

    Args:
        comprehension: Internal comprehension expression.

    Raises:
        ExpressionTypeException: Invalid set comprehension result type,
            typically a [`KVPair`][synt.tokens.kv_pair.KVPair].
    """
    if isinstance(comprehension, comp_expr.Comprehension):
        comp = comprehension
    elif isinstance(comprehension, comp_expr.ComprehensionBuilder):
        comp = comprehension.build()
    elif isinstance(comprehension, comp_expr.ComprehensionNodeBuilder):
        comp = comprehension.build_comp()
    else:
        raise ValueError(
            "Expect expression of type `Comprehension`, found `Unknown`."
        )

    if comp.elt.expr_type == expr.ExprType.KeyValuePair:
        raise ValueError("Expect expression of type `Atom`, found `KeyValuePair`.")
    self.comprehension = comp
into_code ¤
into_code() -> str
Source code in synt/expr/set.py
def into_code(self) -> str:
    return f"{{{self.comprehension.into_code()}}}"

subscript ¤

slice_ module-attribute ¤

slice_ = Slice

Alias Slice.

Notes

slice is a built-in type in Python, so it's renamed to slice_ with a suffix.

Subscript ¤

Bases: Expression

Subscript operation.

References

Subscription.

Source code in synt/expr/subscript.py
class Subscript(expr.Expression):
    r"""Subscript operation.

    References:
        [Subscription](https://docs.python.org/3/reference/expressions.html#grammar-token-python-grammar-subscription).
    """

    target: expr.Expression
    """Target of the operation."""
    slices: list[Slice | expr.Expression]
    """Slices to index the target."""

    expr_type = expr.ExprType.Subscript
    precedence = expr.ExprPrecedence.Call

    def __init__(
        self, target: expr.IntoExpression, slices: list[Slice | expr.IntoExpression]
    ):
        """Initialize a `Subscript` operation.

        Args:
            target: Target of the operation.
            slices: Slices to index the target.
        """
        self.target = target.into_expression()
        if (
            self.target.precedence > self.precedence
        ):  # special rule here, attr call doesn't need a wrap
            self.target = self.target.wrapped()
        self.slices = [
            s if isinstance(s, Slice) else s.into_expression() for s in slices
        ]

    def into_code(self) -> str:
        slice_text = ", ".join(x.into_code() for x in self.slices)
        return f"{self.target.into_code()}[{slice_text}]"
expr_type class-attribute instance-attribute ¤
expr_type = Subscript
precedence class-attribute instance-attribute ¤
precedence = Call
target instance-attribute ¤
target: Expression = into_expression()

Target of the operation.

slices instance-attribute ¤
1
2
3
4
slices: list[Slice | Expression] = [
    s if isinstance(s, Slice) else into_expression()
    for s in slices
]

Slices to index the target.

__init__ ¤
1
2
3
4
__init__(
    target: IntoExpression,
    slices: list[Slice | IntoExpression],
)

Initialize a Subscript operation.

Parameters:

Name Type Description Default
target IntoExpression

Target of the operation.

required
slices list[Slice | IntoExpression]

Slices to index the target.

required
Source code in synt/expr/subscript.py
def __init__(
    self, target: expr.IntoExpression, slices: list[Slice | expr.IntoExpression]
):
    """Initialize a `Subscript` operation.

    Args:
        target: Target of the operation.
        slices: Slices to index the target.
    """
    self.target = target.into_expression()
    if (
        self.target.precedence > self.precedence
    ):  # special rule here, attr call doesn't need a wrap
        self.target = self.target.wrapped()
    self.slices = [
        s if isinstance(s, Slice) else s.into_expression() for s in slices
    ]
into_code ¤
into_code() -> str
Source code in synt/expr/subscript.py
def into_code(self) -> str:
    slice_text = ", ".join(x.into_code() for x in self.slices)
    return f"{self.target.into_code()}[{slice_text}]"

Slice ¤

Bases: IntoCode

Slice constructor.

1
2
3
4
5
foo[
    5     # lower
    :10   # upper
    :2    # step (optional)
]

Examples:

1
2
3
4
sl = slice_(litint(5), litint(10))
assert sl.into_code() == "5:10"
sl = slice_(litint(5), litint(10), id_("a"))
assert sl.into_code() == "5:10:a"
References

Slice.

Source code in synt/expr/subscript.py
class Slice(code.IntoCode):
    r"""Slice constructor.

    ```python
    foo[
        5     # lower
        :10   # upper
        :2    # step (optional)
    ]
    ```

    Examples:
        ```python
        sl = slice_(litint(5), litint(10))
        assert sl.into_code() == "5:10"
        sl = slice_(litint(5), litint(10), id_("a"))
        assert sl.into_code() == "5:10:a"
        ```

    References:
        [Slice](https://docs.python.org/3/library/ast.html#ast.Slice).
    """

    lower: expr.Expression
    """Lower bound of the slice."""
    upper: expr.Expression
    """Upper bound of the slice."""
    step: expr.Expression | None
    """Step of the slice."""

    def __init__(
        self,
        lower: expr.IntoExpression,
        upper: expr.IntoExpression,
        step: expr.IntoExpression | None = None,
    ):
        """Initialize the slice.

        Args:
            lower: Lower bound of the slice.
            upper: Upper bound of the slice.
            step: Step of the slice.
        """
        self.lower = lower.into_expression()
        self.upper = upper.into_expression()
        self.step = step.into_expression() if step else None

    def into_code(self) -> str:
        if self.step:
            return f"{self.lower.into_code()}:{self.upper.into_code()}:{self.step.into_code()}"
        else:
            return f"{self.lower.into_code()}:{self.upper.into_code()}"
lower instance-attribute ¤
lower: Expression = into_expression()

Lower bound of the slice.

upper instance-attribute ¤
upper: Expression = into_expression()

Upper bound of the slice.

step instance-attribute ¤
1
2
3
step: Expression | None = (
    into_expression() if step else None
)

Step of the slice.

__init__ ¤
1
2
3
4
5
__init__(
    lower: IntoExpression,
    upper: IntoExpression,
    step: IntoExpression | None = None,
)

Initialize the slice.

Parameters:

Name Type Description Default
lower IntoExpression

Lower bound of the slice.

required
upper IntoExpression

Upper bound of the slice.

required
step IntoExpression | None

Step of the slice.

None
Source code in synt/expr/subscript.py
def __init__(
    self,
    lower: expr.IntoExpression,
    upper: expr.IntoExpression,
    step: expr.IntoExpression | None = None,
):
    """Initialize the slice.

    Args:
        lower: Lower bound of the slice.
        upper: Upper bound of the slice.
        step: Step of the slice.
    """
    self.lower = lower.into_expression()
    self.upper = upper.into_expression()
    self.step = step.into_expression() if step else None
into_code ¤
into_code() -> str
Source code in synt/expr/subscript.py
def into_code(self) -> str:
    if self.step:
        return f"{self.lower.into_code()}:{self.upper.into_code()}:{self.step.into_code()}"
    else:
        return f"{self.lower.into_code()}:{self.upper.into_code()}"

tuple ¤

tuple_ module-attribute ¤

tuple_ = Tuple

Alias Tuple.

tup module-attribute ¤

tup = Tuple

Alias Tuple.

Tuple ¤

Bases: Expression

Tuple expression.

Examples:

t = tup(litstr("abc"))
assert t.into_code() == "('abc',)"
Source code in synt/expr/tuple.py
class Tuple(expr.Expression):
    r"""Tuple expression.

    Examples:
        ```python
        t = tup(litstr("abc"))
        assert t.into_code() == "('abc',)"
        ```
    """

    items: list[expr.Expression]
    """Tuple items."""

    precedence = expr.ExprPrecedence.Atom
    expr_type = expr.ExprType.Tuple

    def __init__(self, *items: expr.IntoExpression):
        """Initialize a tuple expression.

        Args:
            items: Tuple items.
        """
        self.items = [i.into_expression() for i in items]

    def into_code(self) -> str:
        return f"({self.into_code_implicit()})"

    def into_code_implicit(self) -> str:
        """Convert the tuple into a string representation implicitly, omitting the parentheses."""
        item_text = ", ".join(x.into_code() for x in self.items)
        if len(self.items) == 1:
            item_text += ","
        return item_text
precedence class-attribute instance-attribute ¤
precedence = Atom
expr_type class-attribute instance-attribute ¤
expr_type = Tuple
items instance-attribute ¤
1
2
3
items: list[Expression] = [
    into_expression() for i in items
]

Tuple items.

__init__ ¤
__init__(*items: IntoExpression)

Initialize a tuple expression.

Parameters:

Name Type Description Default
items IntoExpression

Tuple items.

()
Source code in synt/expr/tuple.py
def __init__(self, *items: expr.IntoExpression):
    """Initialize a tuple expression.

    Args:
        items: Tuple items.
    """
    self.items = [i.into_expression() for i in items]
into_code ¤
into_code() -> str
Source code in synt/expr/tuple.py
def into_code(self) -> str:
    return f"({self.into_code_implicit()})"
into_code_implicit ¤
into_code_implicit() -> str

Convert the tuple into a string representation implicitly, omitting the parentheses.

Source code in synt/expr/tuple.py
def into_code_implicit(self) -> str:
    """Convert the tuple into a string representation implicitly, omitting the parentheses."""
    item_text = ", ".join(x.into_code() for x in self.items)
    if len(self.items) == 1:
        item_text += ","
    return item_text

type_check ¤

is_into_expr ¤

is_into_expr(e: Any) -> TypeGuard[IntoExpression]

Whether the expression is an instance of IntoExpression.

Source code in synt/expr/type_check.py
def is_into_expr(e: Any) -> TypeGuard[expr.IntoExpression]:
    r"""Whether the expression is an instance of `IntoExpression`."""
    return isinstance(e, expr.IntoExpression)

is_ident ¤

Whether the expression is an identifier.

Source code in synt/expr/type_check.py
def is_ident(e: expr.Expression) -> TypeGuard[IdentifierExpr]:
    r"""Whether the expression is an identifier."""
    return e.expr_type == expr.ExprType.Identifier

unary_op ¤

awaited module-attribute ¤

awaited = await_

Alias await_.

starred module-attribute ¤

starred = unpack

Alias unpack.

unpack_seq module-attribute ¤

unpack_seq = unpack

Alias unpack.

double_starred module-attribute ¤

double_starred = unpack_kv

Alias unpack_kv.

unpack_dict module-attribute ¤

unpack_dict = unpack_kv

Alias unpack_kv.

neg module-attribute ¤

neg = negative

Alias negative.

bool_not module-attribute ¤

bool_not = not_

Alias not_.

bit_not module-attribute ¤

bit_not = invert

Alias invert.

UnaryOpType ¤

Bases: IntEnum

Unary operator type.

References

expr.ExprPrecedence

Source code in synt/expr/unary_op.py
class UnaryOpType(IntEnum):
    r"""Unary operator type.

    References:
        [`expr.ExprPrecedence`][synt.expr.expr.ExprPrecedence]
    """

    Await = 0
    """Await expression operator `await`.

    Notes:
        `await` is a Python hard keyword, but synt treats it as a unary operator.
    """

    Yield = 1
    """Yield expression operator `yield`.

    Notes:
        `yield` is a Python hard keyword, but synt treats it as a unary operator.
    """

    YieldFrom = 2
    """Yield-from expression operator `yield from`.

    Notes:
        `yield from` is a Python hard keyword group, but synt treats it as a single unary operator.
    """

    Starred = 3
    """Tuple/list extractor operator `*`."""

    DoubleStarred = 4
    """Dict/mapping extractor operator `**`."""

    Positive = 5
    """Positive operator `+`."""

    Neg = 6
    """Negative operator `-`."""

    BitNot = 7
    """Bitwise NOT operator `~`."""

    BoolNot = 8
    """Boolean NOT operator `not`."""

    def to_precedence(self) -> expr.ExprPrecedence:
        """Get the operator's backend expression's precedence."""
        match self:
            case (
                UnaryOpType.Starred
                | UnaryOpType.DoubleStarred
                | UnaryOpType.Yield
                | UnaryOpType.YieldFrom
            ):
                return expr.ExprPrecedence.Atom
            case UnaryOpType.Await:
                return expr.ExprPrecedence.Await
            case UnaryOpType.Positive | UnaryOpType.Neg | UnaryOpType.BitNot:
                return expr.ExprPrecedence.Unary
            case UnaryOpType.BoolNot:
                return expr.ExprPrecedence.BoolNot
            case _:
                raise ValueError(
                    f"Unexpected unary operator type: {self} [{self.value}]"
                )

    def into_code(self) -> str:
        """Converts the operator into a string representation.

        Raises:
            ValueError: If the operator is not recognized.
        """
        match self:
            case UnaryOpType.Starred:
                return "*"
            case UnaryOpType.DoubleStarred:
                return "**"
            case UnaryOpType.Yield:
                return "yield"
            case UnaryOpType.YieldFrom:
                return "yield from"
            case UnaryOpType.Await:
                return "await"
            case UnaryOpType.Positive:
                return "+"
            case UnaryOpType.Neg:
                return "-"
            case UnaryOpType.BitNot:
                return "~"
            case UnaryOpType.BoolNot:
                return "not"
Await class-attribute instance-attribute ¤
Await = 0

Await expression operator await.

Notes

await is a Python hard keyword, but synt treats it as a unary operator.

Yield class-attribute instance-attribute ¤
Yield = 1

Yield expression operator yield.

Notes

yield is a Python hard keyword, but synt treats it as a unary operator.

YieldFrom class-attribute instance-attribute ¤
YieldFrom = 2

Yield-from expression operator yield from.

Notes

yield from is a Python hard keyword group, but synt treats it as a single unary operator.

Starred class-attribute instance-attribute ¤
Starred = 3

Tuple/list extractor operator *.

DoubleStarred class-attribute instance-attribute ¤
DoubleStarred = 4

Dict/mapping extractor operator **.

Positive class-attribute instance-attribute ¤
Positive = 5

Positive operator +.

Neg class-attribute instance-attribute ¤
Neg = 6

Negative operator -.

BitNot class-attribute instance-attribute ¤
BitNot = 7

Bitwise NOT operator ~.

BoolNot class-attribute instance-attribute ¤
BoolNot = 8

Boolean NOT operator not.

to_precedence ¤
to_precedence() -> ExprPrecedence

Get the operator's backend expression's precedence.

Source code in synt/expr/unary_op.py
def to_precedence(self) -> expr.ExprPrecedence:
    """Get the operator's backend expression's precedence."""
    match self:
        case (
            UnaryOpType.Starred
            | UnaryOpType.DoubleStarred
            | UnaryOpType.Yield
            | UnaryOpType.YieldFrom
        ):
            return expr.ExprPrecedence.Atom
        case UnaryOpType.Await:
            return expr.ExprPrecedence.Await
        case UnaryOpType.Positive | UnaryOpType.Neg | UnaryOpType.BitNot:
            return expr.ExprPrecedence.Unary
        case UnaryOpType.BoolNot:
            return expr.ExprPrecedence.BoolNot
        case _:
            raise ValueError(
                f"Unexpected unary operator type: {self} [{self.value}]"
            )
into_code ¤
into_code() -> str

Converts the operator into a string representation.

Raises:

Type Description
ValueError

If the operator is not recognized.

Source code in synt/expr/unary_op.py
def into_code(self) -> str:
    """Converts the operator into a string representation.

    Raises:
        ValueError: If the operator is not recognized.
    """
    match self:
        case UnaryOpType.Starred:
            return "*"
        case UnaryOpType.DoubleStarred:
            return "**"
        case UnaryOpType.Yield:
            return "yield"
        case UnaryOpType.YieldFrom:
            return "yield from"
        case UnaryOpType.Await:
            return "await"
        case UnaryOpType.Positive:
            return "+"
        case UnaryOpType.Neg:
            return "-"
        case UnaryOpType.BitNot:
            return "~"
        case UnaryOpType.BoolNot:
            return "not"

UnaryOp ¤

Bases: Expression

Unary operation.

Source code in synt/expr/unary_op.py
class UnaryOp(expr.Expression):
    r"""Unary operation."""

    expression: expr.Expression
    """Internal expression."""
    op_type: UnaryOpType
    """Operator type."""
    expr_type = expr.ExprType.UnaryOp

    def __init__(self, op: UnaryOpType, e: expr.IntoExpression):
        """Initialize a unary operation.

        Args:
            op: Unary operator type.
            e: Internal expression.
        """
        self.expression = e.into_expression()
        self.op_type = op

        if self.expression.precedence > self.precedence:
            self.expression = self.expression.wrapped()

    def into_code(self) -> str:
        return f"{self.op_type.into_code()} {self.expression.into_code()}"

    @property
    def precedence(self) -> ExprPrecedence:
        """expr.Expression precedence.

        References:
            [Unary.to_precedence][synt.expr.unary_op.UnaryOpType.to_precedence].
        """
        return self.op_type.to_precedence()
expr_type class-attribute instance-attribute ¤
expr_type = UnaryOp
expression instance-attribute ¤
expression: Expression = into_expression()

Internal expression.

op_type instance-attribute ¤
op_type: UnaryOpType = op

Operator type.

precedence property ¤
precedence: ExprPrecedence

expr.Expression precedence.

References

Unary.to_precedence.

__init__ ¤
__init__(op: UnaryOpType, e: IntoExpression)

Initialize a unary operation.

Parameters:

Name Type Description Default
op UnaryOpType

Unary operator type.

required
e IntoExpression

Internal expression.

required
Source code in synt/expr/unary_op.py
def __init__(self, op: UnaryOpType, e: expr.IntoExpression):
    """Initialize a unary operation.

    Args:
        op: Unary operator type.
        e: Internal expression.
    """
    self.expression = e.into_expression()
    self.op_type = op

    if self.expression.precedence > self.precedence:
        self.expression = self.expression.wrapped()
into_code ¤
into_code() -> str
Source code in synt/expr/unary_op.py
def into_code(self) -> str:
    return f"{self.op_type.into_code()} {self.expression.into_code()}"

await_ ¤

await_(e: IntoExpression) -> UnaryOp

Create an await expression.

Examples:

await_expr = await_(litint(10))
assert await_expr.into_code() == "await 10"
Source code in synt/expr/unary_op.py
def await_(e: expr.IntoExpression) -> UnaryOp:
    r"""Create an `await` expression.

    Examples:
        ```python
        await_expr = await_(litint(10))
        assert await_expr.into_code() == "await 10"
        ```
    """
    return UnaryOp(UnaryOpType.Await, e)

unpack ¤

unpack(e: IntoExpression) -> UnaryOp

Sequence unpacking operation.

Examples:

unpacked_expr = unpack(list_(litint(1), litint(2), litint(3)))
assert unpacked_expr.into_code() == "* [1, 2, 3]"
Source code in synt/expr/unary_op.py
def unpack(e: expr.IntoExpression) -> UnaryOp:
    r"""Sequence unpacking operation.

    Examples:
        ```python
        unpacked_expr = unpack(list_(litint(1), litint(2), litint(3)))
        assert unpacked_expr.into_code() == "* [1, 2, 3]"
        ```
    """
    return UnaryOp(UnaryOpType.Starred, e)

unpack_kv ¤

unpack_kv(e: IntoExpression) -> UnaryOp

K-V pair unpacking operation.

Examples:

unpacked_expr = unpack_kv(dict_(kv(litint(1), litstr('a'))))
assert unpacked_expr.into_code() == "** {1: 'a'}"
Source code in synt/expr/unary_op.py
def unpack_kv(e: expr.IntoExpression) -> UnaryOp:
    r"""K-V pair unpacking operation.

    Examples:
        ```python
        unpacked_expr = unpack_kv(dict_(kv(litint(1), litstr('a'))))
        assert unpacked_expr.into_code() == "** {1: 'a'}"
        ```
    """
    return UnaryOp(UnaryOpType.DoubleStarred, e)

positive ¤

positive(e: IntoExpression) -> UnaryOp

Positive operation.

Examples:

positive_expr = positive(litint(10))
assert positive_expr.into_code() == "+ 10"
Source code in synt/expr/unary_op.py
def positive(e: expr.IntoExpression) -> UnaryOp:
    r"""Positive operation.

    Examples:
        ```python
        positive_expr = positive(litint(10))
        assert positive_expr.into_code() == "+ 10"
        ```
    """
    return UnaryOp(UnaryOpType.Positive, e)

negative ¤

negative(e: IntoExpression) -> UnaryOp

Negative operation.

Examples:

positive_expr = negative(litint(10))
assert positive_expr.into_code() == "- 10"
Source code in synt/expr/unary_op.py
def negative(e: expr.IntoExpression) -> UnaryOp:
    r"""Negative operation.

    Examples:
        ```python
        positive_expr = negative(litint(10))
        assert positive_expr.into_code() == "- 10"
        ```
    """
    return UnaryOp(UnaryOpType.Positive, e)

not_ ¤

Boolean NOT operation.

Examples:

not_expr = not_(id_("foo"))
assert not_expr.into_code() == "not foo"
Source code in synt/expr/unary_op.py
def not_(e: expr.IntoExpression) -> UnaryOp:
    r"""Boolean NOT operation.

    Examples:
        ```python
        not_expr = not_(id_("foo"))
        assert not_expr.into_code() == "not foo"
        ```
    """
    return UnaryOp(UnaryOpType.BoolNot, e)

invert ¤

invert(e: IntoExpression) -> UnaryOp

Bitwise NOT operation.

Examples:

not_expr = invert(id_("foo"))
assert not_expr.into_code() == "~ foo"
Source code in synt/expr/unary_op.py
def invert(e: expr.IntoExpression) -> UnaryOp:
    r"""Bitwise NOT operation.

    Examples:
        ```python
        not_expr = invert(id_("foo"))
        assert not_expr.into_code() == "~ foo"
        ```
    """
    return UnaryOp(UnaryOpType.BitNot, e)

yield_ ¤

yield_(e: Expression) -> UnaryOp

Yield operation.

Examples:

yield_expr = yield_(litint(10))
assert yield_expr.into_code() == "yield 10"
Source code in synt/expr/unary_op.py
def yield_(e: expr.Expression) -> UnaryOp:
    r"""Yield operation.

    Examples:
        ```python
        yield_expr = yield_(litint(10))
        assert yield_expr.into_code() == "yield 10"
        ```
    """
    return UnaryOp(UnaryOpType.Yield, e)

yield_from ¤

yield_from(e: Expression) -> UnaryOp

Yield from operation.

Examples:

yield_expr = yield_from(list_(litint(10), litint(42)))
assert yield_expr.into_code() == "yield from [10, 42]"
Source code in synt/expr/unary_op.py
def yield_from(e: expr.Expression) -> UnaryOp:
    r"""Yield from operation.

    Examples:
        ```python
        yield_expr = yield_from(list_(litint(10), litint(42)))
        assert yield_expr.into_code() == "yield from [10, 42]"
        ```
    """
    return UnaryOp(UnaryOpType.YieldFrom, e)

wrapped ¤

wrapped module-attribute ¤

wrapped = Wrapped

Alias Wrapped.

wrap module-attribute ¤

wrap = Wrapped

Alias Wrapped.

par module-attribute ¤

par = Wrapped

Alias Wrapped.

Wrapped ¤

Bases: Expression

A wrapped expression, aka ( expr ), which is always an atomic expression.

Examples:

wp = wrapped(litint(1) + litint(2)) * litint(3)
assert wp.into_code() == "(1 + 2) * 3"
Notes

Most plain expressions have their own expression precedence, and will be wrapped automatically by Synt. However, for those atomic expressions, some of them does have different parser precedence which is hard to represent beforehand. Thus, you must explicitly wrap them manually.

Source code in synt/expr/wrapped.py
class Wrapped(expr.Expression):
    r"""A wrapped expression, aka `( expr )`, which is always an atomic expression.

    Examples:
        ```python
        wp = wrapped(litint(1) + litint(2)) * litint(3)
        assert wp.into_code() == "(1 + 2) * 3"
        ```

    Notes:
        Most plain expressions have their own expression precedence, and will be wrapped
        automatically by Synt.
        However, for those atomic expressions, some of them does have different parser precedence
        which is hard to represent beforehand. Thus, you must explicitly wrap them manually.
    """

    inner: expr.Expression
    """Inner expression."""

    precedence = expr.ExprPrecedence.Atom
    expr_type = expr.ExprType.Wrapped

    def __init__(self, inner: expr.IntoExpression):
        """Initialize a wrapped expression.

        Args:
            inner: Inner expression.
        """
        self.inner = inner.into_expression()

    def into_code(self) -> str:
        return f"({self.inner.into_code()})"
precedence class-attribute instance-attribute ¤
precedence = Atom
expr_type class-attribute instance-attribute ¤
expr_type = Wrapped
inner instance-attribute ¤
inner: Expression = into_expression()

Inner expression.

__init__ ¤
__init__(inner: IntoExpression)

Initialize a wrapped expression.

Parameters:

Name Type Description Default
inner IntoExpression

Inner expression.

required
Source code in synt/expr/wrapped.py
def __init__(self, inner: expr.IntoExpression):
    """Initialize a wrapped expression.

    Args:
        inner: Inner expression.
    """
    self.inner = inner.into_expression()
into_code ¤
into_code() -> str
Source code in synt/expr/wrapped.py
def into_code(self) -> str:
    return f"({self.inner.into_code()})"

file ¤

File ¤

Abstract file containing arbitrary python code.

Examples:

file = File(
    id_("print").expr().call(litstr("Hello, World!")).stmt(),
    id_("x").expr().assign(litint(42)),
    if_(id_("x").expr().eq(litint(42))).block(
        id_("print").expr().call(litstr("x is 42")).stmt()
    )
)
assert file.into_str() == '''print('Hello, World!')
x = 42
if x == 42:
    print('x is 42')'''
Source code in synt/file.py
class File:
    r"""Abstract file containing arbitrary python code.

    Examples:
        ```python
        file = File(
            id_("print").expr().call(litstr("Hello, World!")).stmt(),
            id_("x").expr().assign(litint(42)),
            if_(id_("x").expr().eq(litint(42))).block(
                id_("print").expr().call(litstr("x is 42")).stmt()
            )
        )
        assert file.into_str() == '''print('Hello, World!')
        x = 42
        if x == 42:
            print('x is 42')'''
        ```
    """

    body: Block
    """Code lines in the file."""

    def __init__(self, *statements: Statement):
        """Initialize a file.

        Args:
            statements: Statements to include in the file.
        """
        self.body = Block(*statements)

    def into_str(self, indent_atom: str = "    ", indent_width: int = 0) -> str:
        """Convert the file into a string.

        Args:
            indent_width: number of `indent_atom`s per indentation level.
            indent_atom: string to use for indentation. E.g. `\\t`, whitespace, etc.
        """
        return self.body.indented(indent_width, indent_atom)

body instance-attribute ¤

body: Block = Block(*statements)

Code lines in the file.

__init__ ¤

__init__(*statements: Statement)

Initialize a file.

Parameters:

Name Type Description Default
statements Statement

Statements to include in the file.

()
Source code in synt/file.py
def __init__(self, *statements: Statement):
    """Initialize a file.

    Args:
        statements: Statements to include in the file.
    """
    self.body = Block(*statements)

into_str ¤

1
2
3
into_str(
    indent_atom: str = "    ", indent_width: int = 0
) -> str

Convert the file into a string.

Parameters:

Name Type Description Default
indent_width int

number of indent_atoms per indentation level.

0
indent_atom str

string to use for indentation. E.g. \t, whitespace, etc.

' '
Source code in synt/file.py
def into_str(self, indent_atom: str = "    ", indent_width: int = 0) -> str:
    """Convert the file into a string.

    Args:
        indent_width: number of `indent_atom`s per indentation level.
        indent_atom: string to use for indentation. E.g. `\\t`, whitespace, etc.
    """
    return self.body.indented(indent_width, indent_atom)

prelude ¤

Synt Prelude¤

This module contains multiple utilities that is often used when working with Synt.

It's suggested to import everything from this module instead of writing several separate import statements.

lambda_ module-attribute ¤

lambda_ = ClosureBuilder

dict_ module-attribute ¤

dict_ = DictVerbatim

Alias DictVerbatim.

Notes

dict is a built-in type in Python, so it's renamed to dict_ with a suffix.

dict_comp module-attribute ¤

dict_comp = DictComprehension

EMPTY module-attribute ¤

EMPTY = Empty()

An instance of Empty.

NULL module-attribute ¤

NULL = Empty()

An instance of Empty.

empty module-attribute ¤

empty = Empty

Alias Empty.

expr module-attribute ¤

expr = Empty

Alias Empty.

null module-attribute ¤

null = Empty

Alias Empty.

fnode module-attribute ¤

fnode = FormatNode

Alias FormatNode.

fstring module-attribute ¤

fstring = FormatString

Alias FormatString.

list_ module-attribute ¤

list_ = ListVerbatim

Alias ListVerbatim.

Notes

list is a built-in type in Python, so it's renamed to list_ with a suffix.

list_comp module-attribute ¤

list_comp = ListComprehension

path module-attribute ¤

path = ModPath

Alias ModPath.

set_ module-attribute ¤

set_ = SetVerbatim

Alias SetVerbatim.

Notes

set is a built-in type in Python, so it's renamed to set_ with a suffix.

set_comp module-attribute ¤

set_comp = SetComprehension

slice_ module-attribute ¤

slice_ = Slice

Alias Slice.

Notes

slice is a built-in type in Python, so it's renamed to slice_ with a suffix.

tup module-attribute ¤

tup = Tuple

Alias Tuple.

tuple_ module-attribute ¤

tuple_ = Tuple

Alias Tuple.

awaited module-attribute ¤

awaited = await_

Alias await_.

bit_not module-attribute ¤

bit_not = invert

Alias invert.

bool_not module-attribute ¤

bool_not = not_

Alias not_.

double_starred module-attribute ¤

double_starred = unpack_kv

Alias unpack_kv.

neg module-attribute ¤

neg = negative

Alias negative.

starred module-attribute ¤

starred = unpack

Alias unpack.

unpack_dict module-attribute ¤

unpack_dict = unpack_kv

Alias unpack_kv.

unpack_seq module-attribute ¤

unpack_seq = unpack

Alias unpack.

par module-attribute ¤

par = Wrapped

Alias Wrapped.

wrap module-attribute ¤

wrap = Wrapped

Alias Wrapped.

wrapped module-attribute ¤

wrapped = Wrapped

Alias Wrapped.

assert_ module-attribute ¤

assert_ = Assert

Alias Assert.

with_ module-attribute ¤

with_ = WithBuilder

Alias WithBuilder.

with_item module-attribute ¤

with_item = WithItem

Alias WithItem.

dec module-attribute ¤

del_ module-attribute ¤

del_ = Delete

Alias Delete.

arg module-attribute ¤

arg = FnArg

Alias FnArg.

from_ module-attribute ¤

import_ module-attribute ¤

import_ = Import

Alias Import.

BREAK module-attribute ¤

BREAK = KeywordStatement('break')

CONTINUE module-attribute ¤

CONTINUE = KeywordStatement('continue')

PASS module-attribute ¤

PASS = KeywordStatement('pass')

for_ module-attribute ¤

while_ module-attribute ¤

match_ module-attribute ¤

match_ = Match

Alias Match.

global_ module-attribute ¤

global_ = Global

Alias Global.

nonlocal_ module-attribute ¤

nonlocal_ = Nonlocal

Alias Nonlocal.

raise_ module-attribute ¤

raise_ = Raise

Alias Raise.

ret module-attribute ¤

ret = Return

Alias Return.

return_ module-attribute ¤

return_ = Return

Alias Return.

id_ module-attribute ¤

Alias Identifier.

Notes

id is a built-in function in Python, so it's renamed to id_ with a suffix.

kv module-attribute ¤

kv = KVPair

Alias for KVPair.

pair module-attribute ¤

pair = KVPair

Alias for KVPair.

ELLIPSIS module-attribute ¤

ELLIPSIS = Literal('...')

Alias for a literal ellipsis ....

FALSE module-attribute ¤

FALSE = bool_(False)

Alias for bool_(False).

NONE module-attribute ¤

NONE = Literal('None')

Alias for a literal None.

TRUE module-attribute ¤

TRUE = bool_(True)

Alias for bool_(True).

UNDERSCORE module-attribute ¤

UNDERSCORE = Literal('_')

Alias for a literal underscore _.

litbool module-attribute ¤

litbool = bool_

Alias for bool_.

litfloat module-attribute ¤

litfloat = float_

Alias for float_.

litint module-attribute ¤

litint = int_

Alias for int_.

litstr module-attribute ¤

litstr = str_

Alias for str_.

tspec module-attribute ¤

Alias TypeParamSpec.

ttup module-attribute ¤

Alias TypeVarTuple.

tvar module-attribute ¤

tvar = TypeVar

Alias TypeVar.

Expression ¤

Bases: IntoExpression, IntoCode

Base class for any expression in Python.

Source code in synt/expr/expr.py
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
class Expression(IntoExpression, code.IntoCode, metaclass=ABCMeta):
    r"""Base class for any expression in Python."""

    @property
    @abstractmethod
    def precedence(self) -> ExprPrecedence:
        """The expression's precedence."""

    @property
    @abstractmethod
    def expr_type(self) -> ExprType:
        """The expression's type."""

    @abstractmethod
    def into_code(self) -> str:
        """Convert the expression into Python code.

        **No Formatting!**
        """

    def into_expression(self) -> Expression:
        """An `Expression` can always be converted into an `Expression`."""
        return self

    def ensure_identifier(self) -> Identifier:
        """Ensure that the expression is an identifier and returns it.

        Raises:
            ValueError: If the expression is not an identifier.
        """
        if type_check.is_ident(self):
            return self.ident
        else:
            raise ValueError("Expression is not an identifier")

    # alias for binary operation

    # bin op > plain method

    def add(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Add operation.

        Examples:
            ```python
            e = litint(1).add(id_("foo")) # alias ... + ...
            assert e.into_code() == "1 + foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Add, self, other)

    def sub(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Subtract operation.

        Examples:
            ```python
            e = litint(1).sub(id_("foo")) # alias ... - ...
            assert e.into_code() == "1 - foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Sub, self, other)

    def mul(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Multiply operation.

        Examples:
            ```python
            e = litint(1).mul(id_("foo")) # alias ... * ...
            assert e.into_code() == "1 * foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Mul, self, other)

    def div(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Divide operation.

        Examples:
            ```python
            e = litint(1).div(id_("foo")) # alias ... / ...
            assert e.into_code() == "1 / foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Div, self, other)

    def truediv(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`div`][synt.expr.expr.Expression.div]."""
        return self.div(other)

    def floor_div(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Floor divide operation.

        Examples:
            ```python
            e = litint(1).floor_div(id_("foo")) # alias ... // ...
            assert e.into_code() == "1 // foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.FloorDiv, self, other)

    def mod(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Modulus operation.

        Examples:
            ```python
            e = litint(1).mod(id_("foo")) # alias ... % ...
            assert e.into_code() == "1 % foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Mod, self, other)

    def pow(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Exponentiation operation.

        Examples:
            ```python
            e = litint(1).pow(id_("foo")) # alias ... ** ...
            assert e.into_code() == "1 ** foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Pow, self, other)

    def at(self, other: IntoExpression) -> binary_op.BinaryOp:
        """At(matrix multiplication) operation.

        Examples:
            ```python
            e = litint(1).at(id_("foo")) # alias ... @ ...
            assert e.into_code() == "1 @ foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.At, self, other)

    def matmul(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`at`][synt.expr.expr.Expression.matmul]."""
        return self.at(other)

    def lshift(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Left shift operation.

        Examples:
            ```python
            e = litint(1).lshift(id_("foo")) # alias ... << ...
            assert e.into_code() == "1 << foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.LShift, self, other)

    def rshift(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Right shift operation.

        Examples:
            ```python
            e = litint(1).rshift(id_("foo")) # alias ... >> ...
            assert e.into_code() == "1 >> foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.RShift, self, other)

    def lt(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Less than operation.

        Examples:
            ```python
            e = litint(1).lt(id_("foo")) # alias ... < ...
            assert e.into_code() == "1 < foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Less, self, other)

    def le(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Less than or equal to operation.

        Examples:
            ```python
            e = litint(1).le(id_("foo")) # alias ... <= ...
            assert e.into_code() == "1 <= foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.LessEqual, self, other)

    def gt(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Greater than operation.

        Examples:
            ```python
            e = litint(1).gt(id_("foo")) # alias ... > ...
            assert e.into_code() == "1 > foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Greater, self, other)

    def ge(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Greater than or equal to operation.

        Examples:
            ```python
            e = litint(1).ge(id_("foo")) # alias ... >= ...
            assert e.into_code() == "1 >= foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.GreaterEqual, self, other)

    def eq(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Equal to operation.

        Examples:
            ```python
            e = litint(1).eq(id_("foo")) # alias ... == ...
            assert e.into_code() == "1 == foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Equal, self, other)

    def ne(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Not equal to operation.

        Examples:
            ```python
            e = litint(1).ne(id_("foo")) # alias ... != ...
            assert e.into_code() == "1 != foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.NotEqual, self, other)

    def in_(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Membership test operation.

        Examples:
            ```python
            e = litint(1).in_(id_("foo")) # builtin check, no alias
            assert e.into_code() == "1 in foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.In, self, other)

    def not_in(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Negative membership test operation.

        Examples:
            ```python
            e = litint(1).not_in(id_("foo")) # builtin check, no alias
            assert e.into_code() == "1 not in foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.NotIn, self, other)

    def is_(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Identity test operation.

        Examples:
            ```python
            e = litint(1).is_(id_("foo")) # builtin check, no alias
            assert e.into_code() == "1 is foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.Is, self, other)

    def is_not(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Negative identity test operation.

        Examples:
            ```python
            e = litint(1).is_not(id_("foo")) # builtin check, no alias
            assert e.into_code() == "1 is not foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.IsNot, self, other)

    def bool_and(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Boolean AND operation.

        Examples:
            ```python
            e = litint(1).bool_and(id_("foo")) # builtin operation, no alias
            assert e.into_code() == "1 and foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.BoolAnd, self, other)

    def bool_or(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Boolean OR operation.

        Examples:
            ```python
            e = litint(1).bool_or(id_("foo")) # builtin operation, no alias
            assert e.into_code() == "1 or foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.BoolOr, self, other)

    def bit_and(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Bitwise AND operation.

        Examples:
            ```python
            e = litint(1).bit_and(id_("foo")) # alias ... & ...
            assert e.into_code() == "1 & foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.BitAnd, self, other)

    def bit_or(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Bitwise OR operation.

        Examples:
            ```python
            e = litint(1).bit_or(id_("foo")) # alias ... | ...
            assert e.into_code() == "1 | foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.BitOr, self, other)

    def bit_xor(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Bitwise XOR operation.

        Examples:
            ```python
            e = litint(1).bit_xor(id_("foo")) # alias ... ^ ...
            assert e.into_code() == "1 ^ foo"
            ```
        """
        return binary_op.BinaryOp(binary_op.BinaryOpType.BitXor, self, other)

    # bin op > magic method

    def __lt__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`lt`][synt.expr.expr.Expression.lt]."""
        return self.lt(other)

    def __le__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`le`][synt.expr.expr.Expression.le]."""
        return self.le(other)

    def __gt__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`gt`][synt.expr.expr.Expression.gt]."""
        return self.gt(other)

    def __ge__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`ge`][synt.expr.expr.Expression.ge]."""
        return self.ge(other)

    def __eq__(self, other: IntoExpression) -> binary_op.BinaryOp:  # type:ignore[override]
        """Alias [`eq`][synt.expr.expr.Expression.eq]."""
        return self.eq(other)

    def __ne__(self, other: IntoExpression) -> binary_op.BinaryOp:  # type:ignore[override]
        """Alias [`ne`][synt.expr.expr.Expression.ne]."""
        return self.ne(other)

    def __lshift__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`lshift`][synt.expr.expr.Expression.lshift]."""
        return self.lshift(other)

    def __rshift__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`rshift`][synt.expr.expr.Expression.rshift]."""
        return self.rshift(other)

    def __and__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`bit_and`][synt.expr.expr.Expression.bit_and]."""
        return self.bit_and(other)

    def __or__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`bit_or`][synt.expr.expr.Expression.bit_or]."""
        return self.bit_or(other)

    def __xor__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`bit_xor`][synt.expr.expr.Expression.bit_xor]."""
        return self.bit_xor(other)

    def __add__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`add`][synt.expr.expr.Expression.add]."""
        return self.add(other)

    def __sub__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`sub`][synt.expr.expr.Expression.sub]."""
        return self.sub(other)

    def __mul__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`mul`][synt.expr.expr.Expression.mul]."""
        return self.mul(other)

    def __truediv__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`div`][synt.expr.expr.Expression.div]."""
        return self.div(other)

    def __floordiv__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`floor_div`][synt.expr.expr.Expression.floor_div]."""
        return self.floor_div(other)

    def __mod__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`mod`][synt.expr.expr.Expression.mod]."""
        return self.mod(other)

    def __matmul__(self, other: IntoExpression) -> binary_op.BinaryOp:
        """Alias [`at`][synt.expr.expr.Expression.at]."""
        return self.at(other)

    # alias for unary operation

    # unary op > plain method

    def positive(self) -> unary_op.UnaryOp:
        """Positive operation, alias [`positive` function][synt.expr.unary_op.positive]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Positive, self)

    def negative(self) -> unary_op.UnaryOp:
        """Negative operation, alias [`negative` function][synt.expr.unary_op.negative]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Neg, self)

    def neg(self) -> unary_op.UnaryOp:
        """Alias [`negative`][synt.expr.expr.Expression.negative]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Neg, self)

    def not_(self) -> unary_op.UnaryOp:
        """Boolean NOT operation, alias [`not_` function][synt.expr.unary_op.not_]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.BoolNot, self)

    def bool_not(self) -> unary_op.UnaryOp:
        """Alias [`not_`][synt.expr.expr.Expression.not_]."""
        return self.not_()

    def invert(self) -> unary_op.UnaryOp:
        """Bitwise NOT operation, alias [`invert` function][synt.expr.unary_op.invert]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.BitNot, self)

    def bit_not(self) -> unary_op.UnaryOp:
        """Alias [`invert`][synt.expr.expr.Expression.invert]."""
        return self.invert()

    def await_(self) -> unary_op.UnaryOp:
        """Await operation, alias [`await_` function][synt.expr.unary_op.await_]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Await, self)

    def awaited(self) -> unary_op.UnaryOp:
        """Alias [`await_`][synt.expr.expr.Expression.await_]"""
        return self.await_()

    def unpack(self) -> unary_op.UnaryOp:
        """Sequence unpacking operation, Alias [`unpack` function][synt.expr.unary_op.unpack]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Starred, self)

    def starred(self) -> unary_op.UnaryOp:
        """Alias [`unpack`][synt.expr.expr.Expression.unpack]."""
        return self.unpack()

    def unpack_seq(self) -> unary_op.UnaryOp:
        """Alias [`unpack`][synt.expr.expr.Expression.unpack]."""
        return self.unpack()

    def unpack_kv(self) -> unary_op.UnaryOp:
        """K-V pair unpacking operation, Alias [`unpack_kv` function][synt.expr.unary_op.unpack_kv]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.DoubleStarred, self)

    def double_starred(self) -> unary_op.UnaryOp:
        """Alias [`unpack_kv`][synt.expr.expr.Expression.unpack_kv]."""
        return self.unpack_kv()

    def unpack_dict(self) -> unary_op.UnaryOp:
        """Alias [`unpack_kv`][synt.expr.expr.Expression.unpack_kv]."""
        return self.unpack_kv()

    def yield_(self) -> unary_op.UnaryOp:
        """Yield operation, alias [`yield_` function][synt.expr.unary_op.yield_]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.Yield, self)

    def yield_from(self) -> unary_op.UnaryOp:
        """Yield from operation, alias [`yield_from` function][synt.expr.unary_op.yield_from]."""
        return unary_op.UnaryOp(unary_op.UnaryOpType.YieldFrom, self)

    # unary op > magic method

    def __neg__(self) -> unary_op.UnaryOp:
        """Alias [`neg`][synt.expr.expr.Expression.neg]."""
        return self.neg()

    def __not__(self) -> unary_op.UnaryOp:
        """Alias [`not_`][synt.expr.expr.Expression.not_]."""
        return self.not_()

    def __invert__(self) -> unary_op.UnaryOp:
        """Alias [`invert`][synt.expr.expr.Expression.invert]."""
        return self.invert()

    # alias for named value

    def named(self, expr: IntoExpression) -> named_expr.NamedExpr:
        """Assign the expression to `self`.

        Args:
            expr: The expression to assign.

        Raises:
            ValueError: If `self` is not an identifier.

        Examples:
            ```python
            named_expr = id_('a').expr().named(litint(1))
            assert named_expr.into_code() == "a := 1"
            ```
        """
        return named_expr.NamedExpr(self.ensure_identifier(), expr)

    def named_as(self, target: Identifier) -> named_expr.NamedExpr:
        """Assign self to the target.

        Args:
            target: The target identifier.

        Examples:
            ```python
            named_as_expr = (litint(1) + litint(2)).named_as(id_('a')).is_(TRUE)
            assert named_as_expr.into_code() == "(a := 1 + 2) is True"
            ```
        """
        return named_expr.NamedExpr(target, self)

    # alias for attribute

    def attr(self, attr: str) -> attribute.Attribute:
        """attribute.Attribute getting operation.

        Args:
            attr: The attribute name.

        Examples:
            ```python
            attr_expr = id_('a').expr().attr('b').expr().call(litint(1), litint(2))
            assert attr_expr.into_code() == "a.b(1, 2)"
            ```
        """
        return attribute.Attribute(self, attr)

    # alias for call

    def call(
        self,
        *args: IntoExpression | tuple[Identifier, IntoExpression],
        **kwargs: IntoExpression,
    ) -> call.Call:
        """Calling a function or object.

        Args:
            *args: Positional arguments.
            **kwargs: Keyword arguments.

        Raises:
            ValueError: If any argument is not [`IntoExpression`][synt.expr.expr.IntoExpression].

        Examples:
            ```python
            call_expr = id_('a').expr().call(litint(1), litint(2)).call(kw=litint(3))
            assert call_expr.into_code() == "a(1, 2)(kw=3)"
            ```
            With dynamic keyword arguments:
            ```python
            call_expr = id_('a').expr().call(kwarg(id_('b'), litint(42)))
            assert call_expr.into_code() == "a(b=42)"
            ```
        """
        from synt.tokens.ident import Identifier

        kwarg: list[call.Keyword] = []
        arg: list[IntoExpression] = []
        for a in args:
            if isinstance(a, tuple):
                kwarg.append(call.Keyword(a[0], a[1]))
                continue
            if type_check.is_into_expr(a):
                arg.append(a)
                continue
            raise ValueError(f"Invalid argument: {a}")

        for k, v in kwargs.items():
            kwarg.append(call.Keyword(Identifier(k), v))

        return call.Call(self, arg, kwarg)

    # alias for comprehension

    def for_(self, *target: Identifier) -> comprehension.ComprehensionNodeBuilder:
        """Initialize a new comprehension.

        Args:
            target: The target of the iteration.

        Examples:
            ```python
            # `comp_expr` here only implements `IntoExpression` and `IntoCode`
            # because it's still a non-finished builder
            comp_expr = list_comp(id_('x').expr()
                .for_(id_('x')).in_(id_('range').expr().call(litint(5)))
                .if_((id_('x').expr() % litint(2)) == litint(0)))
            assert comp_expr.into_code() == "[x for x in range(5) if x % 2 == 0]"
            ```
        """
        return comprehension.ComprehensionBuilder.init(self, list(target), False)

    def async_for(self, *target: Identifier) -> comprehension.ComprehensionNodeBuilder:
        """Initialize a new async comprehension.

        Args:
            target: The iterator expression of the comprehension.

        Examples:
            ```python
            # `comp_expr` here only implements `IntoExpression` and `IntoCode`
            # because it's still a non-finished builder
            comp_expr = list_comp(id_('x').expr()
                .async_for(id_('x')).in_(id_('range').expr().call(litint(5)))
                .if_((id_('x').expr() % litint(2)) == litint(0)))
            assert comp_expr.into_code() == "[x async for x in range(5) if x % 2 == 0]"
            ```
        """
        return comprehension.ComprehensionBuilder.init(self, list(target), True)

    # alias for condition

    def if_(self, cond: IntoExpression) -> condition.ConditionBuilder:
        """Initialize a new condition expression.

        Args:
            cond: The condition expression.

        Examples:
            ```python
            cond_expr = id_('a').expr().if_(id_('b').expr() > litint(0)).else_(litstr('foo'))
            assert cond_expr.into_code() == "a if b > 0 else 'foo'"
            ```
        """
        return condition.ConditionBuilder(cond, self)

    # alias for subscript

    # subscript > plain method

    def subscribe(
        self, *slices: subscript.Slice | IntoExpression
    ) -> subscript.Subscript:
        """Subscribe to the expression.

        Args:
            slices: The slice expressions.

        Examples:
            ```python
            subscript_expr = id_('a').expr().subscribe(id_('b').expr(), slice_(litint(2), litint(3)))
            # also alias: ...[...]
            assert subscript_expr.into_code() == "a[b, 2:3]"
            ```
        """
        return subscript.Subscript(self, list(slices))

    # subscript > magic method

    def __getitem__(
        self,
        items: tuple[subscript.Slice | IntoExpression, ...]
        | subscript.Slice
        | IntoExpression,
    ) -> subscript.Subscript:
        """Alias [`subscribe`][synt.expr.expr.Expression.subscribe]."""
        if isinstance(items, tuple):
            return self.subscribe(*items)
        else:
            return self.subscribe(items)

    # wrap

    def wrap(self) -> expr_wrapped.Wrapped:
        """Wrap `self` in a pair of parentheses, alias [`Wrapped`][synt.expr.wrapped.Wrapped]."""
        return expr_wrapped.Wrapped(self)

    def wrapped(self) -> expr_wrapped.Wrapped:
        """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
        return self.wrap()

    def par(self) -> expr_wrapped.Wrapped:
        """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
        return self.wrap()

    def atom(self) -> expr_wrapped.Wrapped:
        """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
        return self.wrap()

    # statement constructors

    # assignment

    def assign(self, value: IntoExpression) -> stmt_assign.Assignment:
        """Create a new assignment statement, take `self` as the target.

        Args:
            value: The value to assign.
        """
        return stmt_assign.Assignment(self).assign(value)

    def assign_to(self, target: IntoExpression) -> stmt_assign.Assignment:
        """Create a new assignment statement, take `self` as the value.

        Args:
            target: The value to be assigned.
        """
        return stmt_assign.Assignment(target.into_expression()).assign(self)

    def type(self, ty: IntoExpression) -> stmt_assign.Assignment:
        """Create a new typed assignment statement, take `self` as the target.

        Args:
            ty: The type of the target.
        """
        return stmt_assign.Assignment(self).type(ty)

    def ty(self, ty: IntoExpression) -> stmt_assign.Assignment:
        """Alias [`type`][synt.expr.expr.Expression.type]."""
        return self.type(ty)

    def stmt(self) -> Statement:
        """Convert the expression into a statement."""
        from synt.stmt.expression import stmt

        return stmt(self)

    def as_(self, target: Identifier) -> Alias:
        """Convert the expression into an alias.

        Args:
            target: The target identifier.
        """
        from synt.expr.alias import Alias

        return Alias(self, target)

precedence abstractmethod property ¤

precedence: ExprPrecedence

The expression's precedence.

expr_type abstractmethod property ¤

expr_type: ExprType

The expression's type.

into_code abstractmethod ¤

into_code() -> str

Convert the expression into Python code.

No Formatting!

Source code in synt/expr/expr.py
@abstractmethod
def into_code(self) -> str:
    """Convert the expression into Python code.

    **No Formatting!**
    """

into_expression ¤

into_expression() -> Expression

An Expression can always be converted into an Expression.

Source code in synt/expr/expr.py
def into_expression(self) -> Expression:
    """An `Expression` can always be converted into an `Expression`."""
    return self

ensure_identifier ¤

ensure_identifier() -> Identifier

Ensure that the expression is an identifier and returns it.

Raises:

Type Description
ValueError

If the expression is not an identifier.

Source code in synt/expr/expr.py
def ensure_identifier(self) -> Identifier:
    """Ensure that the expression is an identifier and returns it.

    Raises:
        ValueError: If the expression is not an identifier.
    """
    if type_check.is_ident(self):
        return self.ident
    else:
        raise ValueError("Expression is not an identifier")

add ¤

add(other: IntoExpression) -> BinaryOp

Add operation.

Examples:

e = litint(1).add(id_("foo")) # alias ... + ...
assert e.into_code() == "1 + foo"
Source code in synt/expr/expr.py
def add(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Add operation.

    Examples:
        ```python
        e = litint(1).add(id_("foo")) # alias ... + ...
        assert e.into_code() == "1 + foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Add, self, other)

sub ¤

sub(other: IntoExpression) -> BinaryOp

Subtract operation.

Examples:

e = litint(1).sub(id_("foo")) # alias ... - ...
assert e.into_code() == "1 - foo"
Source code in synt/expr/expr.py
def sub(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Subtract operation.

    Examples:
        ```python
        e = litint(1).sub(id_("foo")) # alias ... - ...
        assert e.into_code() == "1 - foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Sub, self, other)

mul ¤

mul(other: IntoExpression) -> BinaryOp

Multiply operation.

Examples:

e = litint(1).mul(id_("foo")) # alias ... * ...
assert e.into_code() == "1 * foo"
Source code in synt/expr/expr.py
def mul(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Multiply operation.

    Examples:
        ```python
        e = litint(1).mul(id_("foo")) # alias ... * ...
        assert e.into_code() == "1 * foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Mul, self, other)

div ¤

div(other: IntoExpression) -> BinaryOp

Divide operation.

Examples:

e = litint(1).div(id_("foo")) # alias ... / ...
assert e.into_code() == "1 / foo"
Source code in synt/expr/expr.py
def div(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Divide operation.

    Examples:
        ```python
        e = litint(1).div(id_("foo")) # alias ... / ...
        assert e.into_code() == "1 / foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Div, self, other)

truediv ¤

truediv(other: IntoExpression) -> BinaryOp

Alias div.

Source code in synt/expr/expr.py
def truediv(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`div`][synt.expr.expr.Expression.div]."""
    return self.div(other)

floor_div ¤

floor_div(other: IntoExpression) -> BinaryOp

Floor divide operation.

Examples:

e = litint(1).floor_div(id_("foo")) # alias ... // ...
assert e.into_code() == "1 // foo"
Source code in synt/expr/expr.py
def floor_div(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Floor divide operation.

    Examples:
        ```python
        e = litint(1).floor_div(id_("foo")) # alias ... // ...
        assert e.into_code() == "1 // foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.FloorDiv, self, other)

mod ¤

mod(other: IntoExpression) -> BinaryOp

Modulus operation.

Examples:

e = litint(1).mod(id_("foo")) # alias ... % ...
assert e.into_code() == "1 % foo"
Source code in synt/expr/expr.py
def mod(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Modulus operation.

    Examples:
        ```python
        e = litint(1).mod(id_("foo")) # alias ... % ...
        assert e.into_code() == "1 % foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Mod, self, other)

pow ¤

pow(other: IntoExpression) -> BinaryOp

Exponentiation operation.

Examples:

e = litint(1).pow(id_("foo")) # alias ... ** ...
assert e.into_code() == "1 ** foo"
Source code in synt/expr/expr.py
def pow(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Exponentiation operation.

    Examples:
        ```python
        e = litint(1).pow(id_("foo")) # alias ... ** ...
        assert e.into_code() == "1 ** foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Pow, self, other)

at ¤

at(other: IntoExpression) -> BinaryOp

At(matrix multiplication) operation.

Examples:

e = litint(1).at(id_("foo")) # alias ... @ ...
assert e.into_code() == "1 @ foo"
Source code in synt/expr/expr.py
def at(self, other: IntoExpression) -> binary_op.BinaryOp:
    """At(matrix multiplication) operation.

    Examples:
        ```python
        e = litint(1).at(id_("foo")) # alias ... @ ...
        assert e.into_code() == "1 @ foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.At, self, other)

matmul ¤

matmul(other: IntoExpression) -> BinaryOp

Alias at.

Source code in synt/expr/expr.py
def matmul(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`at`][synt.expr.expr.Expression.matmul]."""
    return self.at(other)

lshift ¤

lshift(other: IntoExpression) -> BinaryOp

Left shift operation.

Examples:

e = litint(1).lshift(id_("foo")) # alias ... << ...
assert e.into_code() == "1 << foo"
Source code in synt/expr/expr.py
def lshift(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Left shift operation.

    Examples:
        ```python
        e = litint(1).lshift(id_("foo")) # alias ... << ...
        assert e.into_code() == "1 << foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.LShift, self, other)

rshift ¤

rshift(other: IntoExpression) -> BinaryOp

Right shift operation.

Examples:

e = litint(1).rshift(id_("foo")) # alias ... >> ...
assert e.into_code() == "1 >> foo"
Source code in synt/expr/expr.py
def rshift(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Right shift operation.

    Examples:
        ```python
        e = litint(1).rshift(id_("foo")) # alias ... >> ...
        assert e.into_code() == "1 >> foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.RShift, self, other)

lt ¤

lt(other: IntoExpression) -> BinaryOp

Less than operation.

Examples:

e = litint(1).lt(id_("foo")) # alias ... < ...
assert e.into_code() == "1 < foo"
Source code in synt/expr/expr.py
def lt(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Less than operation.

    Examples:
        ```python
        e = litint(1).lt(id_("foo")) # alias ... < ...
        assert e.into_code() == "1 < foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Less, self, other)

le ¤

le(other: IntoExpression) -> BinaryOp

Less than or equal to operation.

Examples:

e = litint(1).le(id_("foo")) # alias ... <= ...
assert e.into_code() == "1 <= foo"
Source code in synt/expr/expr.py
def le(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Less than or equal to operation.

    Examples:
        ```python
        e = litint(1).le(id_("foo")) # alias ... <= ...
        assert e.into_code() == "1 <= foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.LessEqual, self, other)

gt ¤

gt(other: IntoExpression) -> BinaryOp

Greater than operation.

Examples:

e = litint(1).gt(id_("foo")) # alias ... > ...
assert e.into_code() == "1 > foo"
Source code in synt/expr/expr.py
def gt(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Greater than operation.

    Examples:
        ```python
        e = litint(1).gt(id_("foo")) # alias ... > ...
        assert e.into_code() == "1 > foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Greater, self, other)

ge ¤

ge(other: IntoExpression) -> BinaryOp

Greater than or equal to operation.

Examples:

e = litint(1).ge(id_("foo")) # alias ... >= ...
assert e.into_code() == "1 >= foo"
Source code in synt/expr/expr.py
def ge(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Greater than or equal to operation.

    Examples:
        ```python
        e = litint(1).ge(id_("foo")) # alias ... >= ...
        assert e.into_code() == "1 >= foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.GreaterEqual, self, other)

eq ¤

eq(other: IntoExpression) -> BinaryOp

Equal to operation.

Examples:

e = litint(1).eq(id_("foo")) # alias ... == ...
assert e.into_code() == "1 == foo"
Source code in synt/expr/expr.py
def eq(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Equal to operation.

    Examples:
        ```python
        e = litint(1).eq(id_("foo")) # alias ... == ...
        assert e.into_code() == "1 == foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Equal, self, other)

ne ¤

ne(other: IntoExpression) -> BinaryOp

Not equal to operation.

Examples:

e = litint(1).ne(id_("foo")) # alias ... != ...
assert e.into_code() == "1 != foo"
Source code in synt/expr/expr.py
def ne(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Not equal to operation.

    Examples:
        ```python
        e = litint(1).ne(id_("foo")) # alias ... != ...
        assert e.into_code() == "1 != foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.NotEqual, self, other)

in_ ¤

in_(other: IntoExpression) -> BinaryOp

Membership test operation.

Examples:

e = litint(1).in_(id_("foo")) # builtin check, no alias
assert e.into_code() == "1 in foo"
Source code in synt/expr/expr.py
def in_(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Membership test operation.

    Examples:
        ```python
        e = litint(1).in_(id_("foo")) # builtin check, no alias
        assert e.into_code() == "1 in foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.In, self, other)

not_in ¤

not_in(other: IntoExpression) -> BinaryOp

Negative membership test operation.

Examples:

e = litint(1).not_in(id_("foo")) # builtin check, no alias
assert e.into_code() == "1 not in foo"
Source code in synt/expr/expr.py
def not_in(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Negative membership test operation.

    Examples:
        ```python
        e = litint(1).not_in(id_("foo")) # builtin check, no alias
        assert e.into_code() == "1 not in foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.NotIn, self, other)

is_ ¤

is_(other: IntoExpression) -> BinaryOp

Identity test operation.

Examples:

e = litint(1).is_(id_("foo")) # builtin check, no alias
assert e.into_code() == "1 is foo"
Source code in synt/expr/expr.py
def is_(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Identity test operation.

    Examples:
        ```python
        e = litint(1).is_(id_("foo")) # builtin check, no alias
        assert e.into_code() == "1 is foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.Is, self, other)

is_not ¤

is_not(other: IntoExpression) -> BinaryOp

Negative identity test operation.

Examples:

e = litint(1).is_not(id_("foo")) # builtin check, no alias
assert e.into_code() == "1 is not foo"
Source code in synt/expr/expr.py
def is_not(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Negative identity test operation.

    Examples:
        ```python
        e = litint(1).is_not(id_("foo")) # builtin check, no alias
        assert e.into_code() == "1 is not foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.IsNot, self, other)

bool_and ¤

bool_and(other: IntoExpression) -> BinaryOp

Boolean AND operation.

Examples:

e = litint(1).bool_and(id_("foo")) # builtin operation, no alias
assert e.into_code() == "1 and foo"
Source code in synt/expr/expr.py
def bool_and(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Boolean AND operation.

    Examples:
        ```python
        e = litint(1).bool_and(id_("foo")) # builtin operation, no alias
        assert e.into_code() == "1 and foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.BoolAnd, self, other)

bool_or ¤

bool_or(other: IntoExpression) -> BinaryOp

Boolean OR operation.

Examples:

e = litint(1).bool_or(id_("foo")) # builtin operation, no alias
assert e.into_code() == "1 or foo"
Source code in synt/expr/expr.py
def bool_or(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Boolean OR operation.

    Examples:
        ```python
        e = litint(1).bool_or(id_("foo")) # builtin operation, no alias
        assert e.into_code() == "1 or foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.BoolOr, self, other)

bit_and ¤

bit_and(other: IntoExpression) -> BinaryOp

Bitwise AND operation.

Examples:

e = litint(1).bit_and(id_("foo")) # alias ... & ...
assert e.into_code() == "1 & foo"
Source code in synt/expr/expr.py
def bit_and(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Bitwise AND operation.

    Examples:
        ```python
        e = litint(1).bit_and(id_("foo")) # alias ... & ...
        assert e.into_code() == "1 & foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.BitAnd, self, other)

bit_or ¤

bit_or(other: IntoExpression) -> BinaryOp

Bitwise OR operation.

Examples:

e = litint(1).bit_or(id_("foo")) # alias ... | ...
assert e.into_code() == "1 | foo"
Source code in synt/expr/expr.py
def bit_or(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Bitwise OR operation.

    Examples:
        ```python
        e = litint(1).bit_or(id_("foo")) # alias ... | ...
        assert e.into_code() == "1 | foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.BitOr, self, other)

bit_xor ¤

bit_xor(other: IntoExpression) -> BinaryOp

Bitwise XOR operation.

Examples:

e = litint(1).bit_xor(id_("foo")) # alias ... ^ ...
assert e.into_code() == "1 ^ foo"
Source code in synt/expr/expr.py
def bit_xor(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Bitwise XOR operation.

    Examples:
        ```python
        e = litint(1).bit_xor(id_("foo")) # alias ... ^ ...
        assert e.into_code() == "1 ^ foo"
        ```
    """
    return binary_op.BinaryOp(binary_op.BinaryOpType.BitXor, self, other)

__lt__ ¤

__lt__(other: IntoExpression) -> BinaryOp

Alias lt.

Source code in synt/expr/expr.py
def __lt__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`lt`][synt.expr.expr.Expression.lt]."""
    return self.lt(other)

__le__ ¤

__le__(other: IntoExpression) -> BinaryOp

Alias le.

Source code in synt/expr/expr.py
def __le__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`le`][synt.expr.expr.Expression.le]."""
    return self.le(other)

__gt__ ¤

__gt__(other: IntoExpression) -> BinaryOp

Alias gt.

Source code in synt/expr/expr.py
def __gt__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`gt`][synt.expr.expr.Expression.gt]."""
    return self.gt(other)

__ge__ ¤

__ge__(other: IntoExpression) -> BinaryOp

Alias ge.

Source code in synt/expr/expr.py
def __ge__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`ge`][synt.expr.expr.Expression.ge]."""
    return self.ge(other)

__eq__ ¤

__eq__(other: IntoExpression) -> BinaryOp

Alias eq.

Source code in synt/expr/expr.py
def __eq__(self, other: IntoExpression) -> binary_op.BinaryOp:  # type:ignore[override]
    """Alias [`eq`][synt.expr.expr.Expression.eq]."""
    return self.eq(other)

__ne__ ¤

__ne__(other: IntoExpression) -> BinaryOp

Alias ne.

Source code in synt/expr/expr.py
def __ne__(self, other: IntoExpression) -> binary_op.BinaryOp:  # type:ignore[override]
    """Alias [`ne`][synt.expr.expr.Expression.ne]."""
    return self.ne(other)

__lshift__ ¤

__lshift__(other: IntoExpression) -> BinaryOp

Alias lshift.

Source code in synt/expr/expr.py
def __lshift__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`lshift`][synt.expr.expr.Expression.lshift]."""
    return self.lshift(other)

__rshift__ ¤

__rshift__(other: IntoExpression) -> BinaryOp

Alias rshift.

Source code in synt/expr/expr.py
def __rshift__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`rshift`][synt.expr.expr.Expression.rshift]."""
    return self.rshift(other)

__and__ ¤

__and__(other: IntoExpression) -> BinaryOp

Alias bit_and.

Source code in synt/expr/expr.py
def __and__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`bit_and`][synt.expr.expr.Expression.bit_and]."""
    return self.bit_and(other)

__or__ ¤

__or__(other: IntoExpression) -> BinaryOp

Alias bit_or.

Source code in synt/expr/expr.py
def __or__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`bit_or`][synt.expr.expr.Expression.bit_or]."""
    return self.bit_or(other)

__xor__ ¤

__xor__(other: IntoExpression) -> BinaryOp

Alias bit_xor.

Source code in synt/expr/expr.py
def __xor__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`bit_xor`][synt.expr.expr.Expression.bit_xor]."""
    return self.bit_xor(other)

__add__ ¤

__add__(other: IntoExpression) -> BinaryOp

Alias add.

Source code in synt/expr/expr.py
def __add__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`add`][synt.expr.expr.Expression.add]."""
    return self.add(other)

__sub__ ¤

__sub__(other: IntoExpression) -> BinaryOp

Alias sub.

Source code in synt/expr/expr.py
def __sub__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`sub`][synt.expr.expr.Expression.sub]."""
    return self.sub(other)

__mul__ ¤

__mul__(other: IntoExpression) -> BinaryOp

Alias mul.

Source code in synt/expr/expr.py
def __mul__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`mul`][synt.expr.expr.Expression.mul]."""
    return self.mul(other)

__truediv__ ¤

__truediv__(other: IntoExpression) -> BinaryOp

Alias div.

Source code in synt/expr/expr.py
def __truediv__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`div`][synt.expr.expr.Expression.div]."""
    return self.div(other)

__floordiv__ ¤

__floordiv__(other: IntoExpression) -> BinaryOp

Alias floor_div.

Source code in synt/expr/expr.py
def __floordiv__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`floor_div`][synt.expr.expr.Expression.floor_div]."""
    return self.floor_div(other)

__mod__ ¤

__mod__(other: IntoExpression) -> BinaryOp

Alias mod.

Source code in synt/expr/expr.py
def __mod__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`mod`][synt.expr.expr.Expression.mod]."""
    return self.mod(other)

__matmul__ ¤

__matmul__(other: IntoExpression) -> BinaryOp

Alias at.

Source code in synt/expr/expr.py
def __matmul__(self, other: IntoExpression) -> binary_op.BinaryOp:
    """Alias [`at`][synt.expr.expr.Expression.at]."""
    return self.at(other)

positive ¤

positive() -> UnaryOp

Positive operation, alias positive function.

Source code in synt/expr/expr.py
def positive(self) -> unary_op.UnaryOp:
    """Positive operation, alias [`positive` function][synt.expr.unary_op.positive]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Positive, self)

negative ¤

negative() -> UnaryOp

Negative operation, alias negative function.

Source code in synt/expr/expr.py
def negative(self) -> unary_op.UnaryOp:
    """Negative operation, alias [`negative` function][synt.expr.unary_op.negative]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Neg, self)

neg ¤

neg() -> UnaryOp

Alias negative.

Source code in synt/expr/expr.py
def neg(self) -> unary_op.UnaryOp:
    """Alias [`negative`][synt.expr.expr.Expression.negative]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Neg, self)

not_ ¤

not_() -> UnaryOp

Boolean NOT operation, alias not_ function.

Source code in synt/expr/expr.py
def not_(self) -> unary_op.UnaryOp:
    """Boolean NOT operation, alias [`not_` function][synt.expr.unary_op.not_]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.BoolNot, self)

bool_not ¤

bool_not() -> UnaryOp

Alias not_.

Source code in synt/expr/expr.py
def bool_not(self) -> unary_op.UnaryOp:
    """Alias [`not_`][synt.expr.expr.Expression.not_]."""
    return self.not_()

invert ¤

invert() -> UnaryOp

Bitwise NOT operation, alias invert function.

Source code in synt/expr/expr.py
def invert(self) -> unary_op.UnaryOp:
    """Bitwise NOT operation, alias [`invert` function][synt.expr.unary_op.invert]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.BitNot, self)

bit_not ¤

bit_not() -> UnaryOp

Alias invert.

Source code in synt/expr/expr.py
def bit_not(self) -> unary_op.UnaryOp:
    """Alias [`invert`][synt.expr.expr.Expression.invert]."""
    return self.invert()

await_ ¤

await_() -> UnaryOp

Await operation, alias await_ function.

Source code in synt/expr/expr.py
def await_(self) -> unary_op.UnaryOp:
    """Await operation, alias [`await_` function][synt.expr.unary_op.await_]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Await, self)

awaited ¤

awaited() -> UnaryOp

Alias await_

Source code in synt/expr/expr.py
def awaited(self) -> unary_op.UnaryOp:
    """Alias [`await_`][synt.expr.expr.Expression.await_]"""
    return self.await_()

unpack ¤

unpack() -> UnaryOp

Sequence unpacking operation, Alias unpack function.

Source code in synt/expr/expr.py
def unpack(self) -> unary_op.UnaryOp:
    """Sequence unpacking operation, Alias [`unpack` function][synt.expr.unary_op.unpack]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Starred, self)

starred ¤

starred() -> UnaryOp

Alias unpack.

Source code in synt/expr/expr.py
def starred(self) -> unary_op.UnaryOp:
    """Alias [`unpack`][synt.expr.expr.Expression.unpack]."""
    return self.unpack()

unpack_seq ¤

unpack_seq() -> UnaryOp

Alias unpack.

Source code in synt/expr/expr.py
def unpack_seq(self) -> unary_op.UnaryOp:
    """Alias [`unpack`][synt.expr.expr.Expression.unpack]."""
    return self.unpack()

unpack_kv ¤

unpack_kv() -> UnaryOp

K-V pair unpacking operation, Alias unpack_kv function.

Source code in synt/expr/expr.py
def unpack_kv(self) -> unary_op.UnaryOp:
    """K-V pair unpacking operation, Alias [`unpack_kv` function][synt.expr.unary_op.unpack_kv]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.DoubleStarred, self)

double_starred ¤

double_starred() -> UnaryOp

Alias unpack_kv.

Source code in synt/expr/expr.py
def double_starred(self) -> unary_op.UnaryOp:
    """Alias [`unpack_kv`][synt.expr.expr.Expression.unpack_kv]."""
    return self.unpack_kv()

unpack_dict ¤

unpack_dict() -> UnaryOp

Alias unpack_kv.

Source code in synt/expr/expr.py
def unpack_dict(self) -> unary_op.UnaryOp:
    """Alias [`unpack_kv`][synt.expr.expr.Expression.unpack_kv]."""
    return self.unpack_kv()

yield_ ¤

yield_() -> UnaryOp

Yield operation, alias yield_ function.

Source code in synt/expr/expr.py
def yield_(self) -> unary_op.UnaryOp:
    """Yield operation, alias [`yield_` function][synt.expr.unary_op.yield_]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.Yield, self)

yield_from ¤

yield_from() -> UnaryOp

Yield from operation, alias yield_from function.

Source code in synt/expr/expr.py
def yield_from(self) -> unary_op.UnaryOp:
    """Yield from operation, alias [`yield_from` function][synt.expr.unary_op.yield_from]."""
    return unary_op.UnaryOp(unary_op.UnaryOpType.YieldFrom, self)

__neg__ ¤

__neg__() -> UnaryOp

Alias neg.

Source code in synt/expr/expr.py
def __neg__(self) -> unary_op.UnaryOp:
    """Alias [`neg`][synt.expr.expr.Expression.neg]."""
    return self.neg()

__not__ ¤

__not__() -> UnaryOp

Alias not_.

Source code in synt/expr/expr.py
def __not__(self) -> unary_op.UnaryOp:
    """Alias [`not_`][synt.expr.expr.Expression.not_]."""
    return self.not_()

__invert__ ¤

__invert__() -> UnaryOp

Alias invert.

Source code in synt/expr/expr.py
def __invert__(self) -> unary_op.UnaryOp:
    """Alias [`invert`][synt.expr.expr.Expression.invert]."""
    return self.invert()

named ¤

named(expr: IntoExpression) -> NamedExpr

Assign the expression to self.

Parameters:

Name Type Description Default
expr IntoExpression

The expression to assign.

required

Raises:

Type Description
ValueError

If self is not an identifier.

Examples:

named_expr = id_('a').expr().named(litint(1))
assert named_expr.into_code() == "a := 1"
Source code in synt/expr/expr.py
def named(self, expr: IntoExpression) -> named_expr.NamedExpr:
    """Assign the expression to `self`.

    Args:
        expr: The expression to assign.

    Raises:
        ValueError: If `self` is not an identifier.

    Examples:
        ```python
        named_expr = id_('a').expr().named(litint(1))
        assert named_expr.into_code() == "a := 1"
        ```
    """
    return named_expr.NamedExpr(self.ensure_identifier(), expr)

named_as ¤

named_as(target: Identifier) -> NamedExpr

Assign self to the target.

Parameters:

Name Type Description Default
target Identifier

The target identifier.

required

Examples:

named_as_expr = (litint(1) + litint(2)).named_as(id_('a')).is_(TRUE)
assert named_as_expr.into_code() == "(a := 1 + 2) is True"
Source code in synt/expr/expr.py
def named_as(self, target: Identifier) -> named_expr.NamedExpr:
    """Assign self to the target.

    Args:
        target: The target identifier.

    Examples:
        ```python
        named_as_expr = (litint(1) + litint(2)).named_as(id_('a')).is_(TRUE)
        assert named_as_expr.into_code() == "(a := 1 + 2) is True"
        ```
    """
    return named_expr.NamedExpr(target, self)

attr ¤

attr(attr: str) -> Attribute

attribute.Attribute getting operation.

Parameters:

Name Type Description Default
attr str

The attribute name.

required

Examples:

attr_expr = id_('a').expr().attr('b').expr().call(litint(1), litint(2))
assert attr_expr.into_code() == "a.b(1, 2)"
Source code in synt/expr/expr.py
def attr(self, attr: str) -> attribute.Attribute:
    """attribute.Attribute getting operation.

    Args:
        attr: The attribute name.

    Examples:
        ```python
        attr_expr = id_('a').expr().attr('b').expr().call(litint(1), litint(2))
        assert attr_expr.into_code() == "a.b(1, 2)"
        ```
    """
    return attribute.Attribute(self, attr)

call ¤

1
2
3
4
5
call(
    *args: IntoExpression
    | tuple[Identifier, IntoExpression],
    **kwargs: IntoExpression
) -> Call

Calling a function or object.

Parameters:

Name Type Description Default
*args IntoExpression | tuple[Identifier, IntoExpression]

Positional arguments.

()
**kwargs IntoExpression

Keyword arguments.

{}

Raises:

Type Description
ValueError

If any argument is not IntoExpression.

Examples:

call_expr = id_('a').expr().call(litint(1), litint(2)).call(kw=litint(3))
assert call_expr.into_code() == "a(1, 2)(kw=3)"
With dynamic keyword arguments:
call_expr = id_('a').expr().call(kwarg(id_('b'), litint(42)))
assert call_expr.into_code() == "a(b=42)"

Source code in synt/expr/expr.py
def call(
    self,
    *args: IntoExpression | tuple[Identifier, IntoExpression],
    **kwargs: IntoExpression,
) -> call.Call:
    """Calling a function or object.

    Args:
        *args: Positional arguments.
        **kwargs: Keyword arguments.

    Raises:
        ValueError: If any argument is not [`IntoExpression`][synt.expr.expr.IntoExpression].

    Examples:
        ```python
        call_expr = id_('a').expr().call(litint(1), litint(2)).call(kw=litint(3))
        assert call_expr.into_code() == "a(1, 2)(kw=3)"
        ```
        With dynamic keyword arguments:
        ```python
        call_expr = id_('a').expr().call(kwarg(id_('b'), litint(42)))
        assert call_expr.into_code() == "a(b=42)"
        ```
    """
    from synt.tokens.ident import Identifier

    kwarg: list[call.Keyword] = []
    arg: list[IntoExpression] = []
    for a in args:
        if isinstance(a, tuple):
            kwarg.append(call.Keyword(a[0], a[1]))
            continue
        if type_check.is_into_expr(a):
            arg.append(a)
            continue
        raise ValueError(f"Invalid argument: {a}")

    for k, v in kwargs.items():
        kwarg.append(call.Keyword(Identifier(k), v))

    return call.Call(self, arg, kwarg)

for_ ¤

Initialize a new comprehension.

Parameters:

Name Type Description Default
target Identifier

The target of the iteration.

()

Examples:

1
2
3
4
5
6
# `comp_expr` here only implements `IntoExpression` and `IntoCode`
# because it's still a non-finished builder
comp_expr = list_comp(id_('x').expr()
    .for_(id_('x')).in_(id_('range').expr().call(litint(5)))
    .if_((id_('x').expr() % litint(2)) == litint(0)))
assert comp_expr.into_code() == "[x for x in range(5) if x % 2 == 0]"
Source code in synt/expr/expr.py
def for_(self, *target: Identifier) -> comprehension.ComprehensionNodeBuilder:
    """Initialize a new comprehension.

    Args:
        target: The target of the iteration.

    Examples:
        ```python
        # `comp_expr` here only implements `IntoExpression` and `IntoCode`
        # because it's still a non-finished builder
        comp_expr = list_comp(id_('x').expr()
            .for_(id_('x')).in_(id_('range').expr().call(litint(5)))
            .if_((id_('x').expr() % litint(2)) == litint(0)))
        assert comp_expr.into_code() == "[x for x in range(5) if x % 2 == 0]"
        ```
    """
    return comprehension.ComprehensionBuilder.init(self, list(target), False)

async_for ¤

async_for(*target: Identifier) -> ComprehensionNodeBuilder

Initialize a new async comprehension.

Parameters:

Name Type Description Default
target Identifier

The iterator expression of the comprehension.

()

Examples:

1
2
3
4
5
6
# `comp_expr` here only implements `IntoExpression` and `IntoCode`
# because it's still a non-finished builder
comp_expr = list_comp(id_('x').expr()
    .async_for(id_('x')).in_(id_('range').expr().call(litint(5)))
    .if_((id_('x').expr() % litint(2)) == litint(0)))
assert comp_expr.into_code() == "[x async for x in range(5) if x % 2 == 0]"
Source code in synt/expr/expr.py
def async_for(self, *target: Identifier) -> comprehension.ComprehensionNodeBuilder:
    """Initialize a new async comprehension.

    Args:
        target: The iterator expression of the comprehension.

    Examples:
        ```python
        # `comp_expr` here only implements `IntoExpression` and `IntoCode`
        # because it's still a non-finished builder
        comp_expr = list_comp(id_('x').expr()
            .async_for(id_('x')).in_(id_('range').expr().call(litint(5)))
            .if_((id_('x').expr() % litint(2)) == litint(0)))
        assert comp_expr.into_code() == "[x async for x in range(5) if x % 2 == 0]"
        ```
    """
    return comprehension.ComprehensionBuilder.init(self, list(target), True)

if_ ¤

Initialize a new condition expression.

Parameters:

Name Type Description Default
cond IntoExpression

The condition expression.

required

Examples:

cond_expr = id_('a').expr().if_(id_('b').expr() > litint(0)).else_(litstr('foo'))
assert cond_expr.into_code() == "a if b > 0 else 'foo'"
Source code in synt/expr/expr.py
def if_(self, cond: IntoExpression) -> condition.ConditionBuilder:
    """Initialize a new condition expression.

    Args:
        cond: The condition expression.

    Examples:
        ```python
        cond_expr = id_('a').expr().if_(id_('b').expr() > litint(0)).else_(litstr('foo'))
        assert cond_expr.into_code() == "a if b > 0 else 'foo'"
        ```
    """
    return condition.ConditionBuilder(cond, self)

subscribe ¤

subscribe(*slices: Slice | IntoExpression) -> Subscript

Subscribe to the expression.

Parameters:

Name Type Description Default
slices Slice | IntoExpression

The slice expressions.

()

Examples:

1
2
3
subscript_expr = id_('a').expr().subscribe(id_('b').expr(), slice_(litint(2), litint(3)))
# also alias: ...[...]
assert subscript_expr.into_code() == "a[b, 2:3]"
Source code in synt/expr/expr.py
def subscribe(
    self, *slices: subscript.Slice | IntoExpression
) -> subscript.Subscript:
    """Subscribe to the expression.

    Args:
        slices: The slice expressions.

    Examples:
        ```python
        subscript_expr = id_('a').expr().subscribe(id_('b').expr(), slice_(litint(2), litint(3)))
        # also alias: ...[...]
        assert subscript_expr.into_code() == "a[b, 2:3]"
        ```
    """
    return subscript.Subscript(self, list(slices))

__getitem__ ¤

1
2
3
4
5
6
7
__getitem__(
    items: (
        tuple[Slice | IntoExpression, ...]
        | Slice
        | IntoExpression
    )
) -> Subscript

Alias subscribe.

Source code in synt/expr/expr.py
def __getitem__(
    self,
    items: tuple[subscript.Slice | IntoExpression, ...]
    | subscript.Slice
    | IntoExpression,
) -> subscript.Subscript:
    """Alias [`subscribe`][synt.expr.expr.Expression.subscribe]."""
    if isinstance(items, tuple):
        return self.subscribe(*items)
    else:
        return self.subscribe(items)

wrap ¤

wrap() -> Wrapped

Wrap self in a pair of parentheses, alias Wrapped.

Source code in synt/expr/expr.py
def wrap(self) -> expr_wrapped.Wrapped:
    """Wrap `self` in a pair of parentheses, alias [`Wrapped`][synt.expr.wrapped.Wrapped]."""
    return expr_wrapped.Wrapped(self)

wrapped ¤

wrapped() -> Wrapped

Alias wrap.

Source code in synt/expr/expr.py
def wrapped(self) -> expr_wrapped.Wrapped:
    """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
    return self.wrap()

par ¤

par() -> Wrapped

Alias wrap.

Source code in synt/expr/expr.py
def par(self) -> expr_wrapped.Wrapped:
    """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
    return self.wrap()

atom ¤

atom() -> Wrapped

Alias wrap.

Source code in synt/expr/expr.py
def atom(self) -> expr_wrapped.Wrapped:
    """Alias [`wrap`][synt.expr.expr.Expression.wrap]."""
    return self.wrap()

assign ¤

assign(value: IntoExpression) -> Assignment

Create a new assignment statement, take self as the target.

Parameters:

Name Type Description Default
value IntoExpression

The value to assign.

required
Source code in synt/expr/expr.py
def assign(self, value: IntoExpression) -> stmt_assign.Assignment:
    """Create a new assignment statement, take `self` as the target.

    Args:
        value: The value to assign.
    """
    return stmt_assign.Assignment(self).assign(value)

assign_to ¤

assign_to(target: IntoExpression) -> Assignment

Create a new assignment statement, take self as the value.

Parameters:

Name Type Description Default
target IntoExpression

The value to be assigned.

required
Source code in synt/expr/expr.py
def assign_to(self, target: IntoExpression) -> stmt_assign.Assignment:
    """Create a new assignment statement, take `self` as the value.

    Args:
        target: The value to be assigned.
    """
    return stmt_assign.Assignment(target.into_expression()).assign(self)

type ¤

Create a new typed assignment statement, take self as the target.

Parameters:

Name Type Description Default
ty IntoExpression

The type of the target.

required
Source code in synt/expr/expr.py
def type(self, ty: IntoExpression) -> stmt_assign.Assignment:
    """Create a new typed assignment statement, take `self` as the target.

    Args:
        ty: The type of the target.
    """
    return stmt_assign.Assignment(self).type(ty)

ty ¤

Alias type.

Source code in synt/expr/expr.py
def ty(self, ty: IntoExpression) -> stmt_assign.Assignment:
    """Alias [`type`][synt.expr.expr.Expression.type]."""
    return self.type(ty)

stmt ¤

stmt() -> Statement

Convert the expression into a statement.

Source code in synt/expr/expr.py
def stmt(self) -> Statement:
    """Convert the expression into a statement."""
    from synt.stmt.expression import stmt

    return stmt(self)

as_ ¤

as_(target: Identifier) -> Alias

Convert the expression into an alias.

Parameters:

Name Type Description Default
target Identifier

The target identifier.

required
Source code in synt/expr/expr.py
def as_(self, target: Identifier) -> Alias:
    """Convert the expression into an alias.

    Args:
        target: The target identifier.
    """
    from synt.expr.alias import Alias

    return Alias(self, target)

IntoExpression ¤

Bases: IntoCode

Abstract class for those that can be converted into an Expression.

Source code in synt/expr/expr.py
class IntoExpression(code.IntoCode, metaclass=ABCMeta):
    r"""Abstract class for those that can be converted into an
    [`Expression`][synt.expr.expr.Expression]."""

    @abstractmethod
    def into_expression(self) -> Expression:
        """Convert the object into an expression."""

    def expr(self) -> Expression:
        """Convert the object into an expression.

        This is a convenience method that calls `into_expression()` and returns the result.
        """
        return self.into_expression()

    def into_code(self) -> str:
        """Convert the object into a code string.

        This is a convenience method that calls `into_expression()` and calls `into_code` on the result.
        """
        return self.into_expression().into_code()

into_expression abstractmethod ¤

into_expression() -> Expression

Convert the object into an expression.

Source code in synt/expr/expr.py
@abstractmethod
def into_expression(self) -> Expression:
    """Convert the object into an expression."""

expr ¤

expr() -> Expression

Convert the object into an expression.

This is a convenience method that calls into_expression() and returns the result.

Source code in synt/expr/expr.py
def expr(self) -> Expression:
    """Convert the object into an expression.

    This is a convenience method that calls `into_expression()` and returns the result.
    """
    return self.into_expression()

into_code ¤

into_code() -> str

Convert the object into a code string.

This is a convenience method that calls into_expression() and calls into_code on the result.

Source code in synt/expr/expr.py
def into_code(self) -> str:
    """Convert the object into a code string.

    This is a convenience method that calls `into_expression()` and calls `into_code` on the result.
    """
    return self.into_expression().into_code()

File ¤

Abstract file containing arbitrary python code.

Examples:

file = File(
    id_("print").expr().call(litstr("Hello, World!")).stmt(),
    id_("x").expr().assign(litint(42)),
    if_(id_("x").expr().eq(litint(42))).block(
        id_("print").expr().call(litstr("x is 42")).stmt()
    )
)
assert file.into_str() == '''print('Hello, World!')
x = 42
if x == 42:
    print('x is 42')'''
Source code in synt/file.py
class File:
    r"""Abstract file containing arbitrary python code.

    Examples:
        ```python
        file = File(
            id_("print").expr().call(litstr("Hello, World!")).stmt(),
            id_("x").expr().assign(litint(42)),
            if_(id_("x").expr().eq(litint(42))).block(
                id_("print").expr().call(litstr("x is 42")).stmt()
            )
        )
        assert file.into_str() == '''print('Hello, World!')
        x = 42
        if x == 42:
            print('x is 42')'''
        ```
    """

    body: Block
    """Code lines in the file."""

    def __init__(self, *statements: Statement):
        """Initialize a file.

        Args:
            statements: Statements to include in the file.
        """
        self.body = Block(*statements)

    def into_str(self, indent_atom: str = "    ", indent_width: int = 0) -> str:
        """Convert the file into a string.

        Args:
            indent_width: number of `indent_atom`s per indentation level.
            indent_atom: string to use for indentation. E.g. `\\t`, whitespace, etc.
        """
        return self.body.indented(indent_width, indent_atom)

body instance-attribute ¤

body: Block = Block(*statements)

Code lines in the file.

__init__ ¤

__init__(*statements: Statement)

Initialize a file.

Parameters:

Name Type Description Default
statements Statement

Statements to include in the file.

()
Source code in synt/file.py
def __init__(self, *statements: Statement):
    """Initialize a file.

    Args:
        statements: Statements to include in the file.
    """
    self.body = Block(*statements)

into_str ¤

1
2
3
into_str(
    indent_atom: str = "    ", indent_width: int = 0
) -> str

Convert the file into a string.

Parameters:

Name Type Description Default
indent_width int

number of indent_atoms per indentation level.

0
indent_atom str

string to use for indentation. E.g. \t, whitespace, etc.

' '
Source code in synt/file.py
def into_str(self, indent_atom: str = "    ", indent_width: int = 0) -> str:
    """Convert the file into a string.

    Args:
        indent_width: number of `indent_atom`s per indentation level.
        indent_atom: string to use for indentation. E.g. `\\t`, whitespace, etc.
    """
    return self.body.indented(indent_width, indent_atom)

Block ¤

Bases: Statement

A Python code block.

Source code in synt/stmt/block.py
class Block(Statement):
    r"""A Python code block."""

    body: list[Statement]
    """Code lines in the block."""

    def __init__(self, *args: Statement):
        """Initialize a new code block.

        Args:
            args: code lines.
        """
        self.body = list(args)

    def indented(self, indent_width: int, indent_atom: str) -> str:
        return "\n".join(
            f"{line.indented(indent_width, indent_atom)}" for line in self.body
        )

body instance-attribute ¤

body: list[Statement] = list(args)

Code lines in the block.

__init__ ¤

__init__(*args: Statement)

Initialize a new code block.

Parameters:

Name Type Description Default
args Statement

code lines.

()
Source code in synt/stmt/block.py
def __init__(self, *args: Statement):
    """Initialize a new code block.

    Args:
        args: code lines.
    """
    self.body = list(args)

indented ¤

indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/block.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    return "\n".join(
        f"{line.indented(indent_width, indent_atom)}" for line in self.body
    )

IntoStatement ¤

Any type that can be converted into a statement.

Source code in synt/stmt/stmt.py
class IntoStatement(metaclass=ABCMeta):
    r"""Any type that can be converted into a statement."""

    @abstractmethod
    def into_statement(self) -> Statement:
        """Convert the object into a statement."""

into_statement abstractmethod ¤

into_statement() -> Statement

Convert the object into a statement.

Source code in synt/stmt/stmt.py
@abstractmethod
def into_statement(self) -> Statement:
    """Convert the object into a statement."""

Statement ¤

Bases: IntoCode, IntoStatement

A base class for any Python statement.

Source code in synt/stmt/stmt.py
class Statement(IntoCode, IntoStatement, metaclass=ABCMeta):
    r"""A base class for any Python statement."""

    def into_statement(self) -> Statement:
        """A statement can always be converted into a statement."""
        return self

    @abstractmethod
    def indented(self, indent_width: int, indent_atom: str) -> str:
        """Return the code block with appropriate indentation.

        Args:
            indent_width: number of `indent_atom`s per indentation level.
            indent_atom: string to use for indentation. E.g. `\\t`, whitespace, etc.

        Returns:
            indented code block.
        """

    def into_code(self) -> str:
        """Convert the object into a code string."""
        return self.indented(0, "    ")

into_statement ¤

into_statement() -> Statement

A statement can always be converted into a statement.

Source code in synt/stmt/stmt.py
def into_statement(self) -> Statement:
    """A statement can always be converted into a statement."""
    return self

indented abstractmethod ¤

indented(indent_width: int, indent_atom: str) -> str

Return the code block with appropriate indentation.

Parameters:

Name Type Description Default
indent_width int

number of indent_atoms per indentation level.

required
indent_atom str

string to use for indentation. E.g. \t, whitespace, etc.

required

Returns:

Type Description
str

indented code block.

Source code in synt/stmt/stmt.py
@abstractmethod
def indented(self, indent_width: int, indent_atom: str) -> str:
    """Return the code block with appropriate indentation.

    Args:
        indent_width: number of `indent_atom`s per indentation level.
        indent_atom: string to use for indentation. E.g. `\\t`, whitespace, etc.

    Returns:
        indented code block.
    """

into_code ¤

into_code() -> str

Convert the object into a code string.

Source code in synt/stmt/stmt.py
def into_code(self) -> str:
    """Convert the object into a code string."""
    return self.indented(0, "    ")

parentpath ¤

parentpath(*names: Identifier) -> ModPath

Initialize a path from its parent (depth = 2).

Parameters:

Name Type Description Default
names Identifier

Names of the path.

()

Examples:

r = parentpath(id_("abc"))
assert r.into_code() == "..abc"
Source code in synt/expr/modpath.py
def parentpath(*names: Identifier) -> ModPath:
    r"""Initialize a path from its parent (`depth = 2`).

    Args:
        names: Names of the path.

    Examples:
        ```python
        r = parentpath(id_("abc"))
        assert r.into_code() == "..abc"
        ```
    """
    return ModPath(*names, depth=2)

relpath ¤

relpath(*names: Identifier) -> ModPath

Initialize a path relatively (depth = 1).

Parameters:

Name Type Description Default
names Identifier

Names of the path.

()

Examples:

r = relpath(id_("abc"))
assert r.into_code() == ".abc"
Source code in synt/expr/modpath.py
def relpath(*names: Identifier) -> ModPath:
    r"""Initialize a path relatively (`depth = 1`).

    Args:
        names: Names of the path.

    Examples:
        ```python
        r = relpath(id_("abc"))
        assert r.into_code() == ".abc"
        ```
    """
    return ModPath(*names, depth=1)

await_ ¤

await_(e: IntoExpression) -> UnaryOp

Create an await expression.

Examples:

await_expr = await_(litint(10))
assert await_expr.into_code() == "await 10"
Source code in synt/expr/unary_op.py
def await_(e: expr.IntoExpression) -> UnaryOp:
    r"""Create an `await` expression.

    Examples:
        ```python
        await_expr = await_(litint(10))
        assert await_expr.into_code() == "await 10"
        ```
    """
    return UnaryOp(UnaryOpType.Await, e)

invert ¤

invert(e: IntoExpression) -> UnaryOp

Bitwise NOT operation.

Examples:

not_expr = invert(id_("foo"))
assert not_expr.into_code() == "~ foo"
Source code in synt/expr/unary_op.py
def invert(e: expr.IntoExpression) -> UnaryOp:
    r"""Bitwise NOT operation.

    Examples:
        ```python
        not_expr = invert(id_("foo"))
        assert not_expr.into_code() == "~ foo"
        ```
    """
    return UnaryOp(UnaryOpType.BitNot, e)

negative ¤

negative(e: IntoExpression) -> UnaryOp

Negative operation.

Examples:

positive_expr = negative(litint(10))
assert positive_expr.into_code() == "- 10"
Source code in synt/expr/unary_op.py
def negative(e: expr.IntoExpression) -> UnaryOp:
    r"""Negative operation.

    Examples:
        ```python
        positive_expr = negative(litint(10))
        assert positive_expr.into_code() == "- 10"
        ```
    """
    return UnaryOp(UnaryOpType.Positive, e)

not_ ¤

Boolean NOT operation.

Examples:

not_expr = not_(id_("foo"))
assert not_expr.into_code() == "not foo"
Source code in synt/expr/unary_op.py
def not_(e: expr.IntoExpression) -> UnaryOp:
    r"""Boolean NOT operation.

    Examples:
        ```python
        not_expr = not_(id_("foo"))
        assert not_expr.into_code() == "not foo"
        ```
    """
    return UnaryOp(UnaryOpType.BoolNot, e)

positive ¤

positive(e: IntoExpression) -> UnaryOp

Positive operation.

Examples:

positive_expr = positive(litint(10))
assert positive_expr.into_code() == "+ 10"
Source code in synt/expr/unary_op.py
def positive(e: expr.IntoExpression) -> UnaryOp:
    r"""Positive operation.

    Examples:
        ```python
        positive_expr = positive(litint(10))
        assert positive_expr.into_code() == "+ 10"
        ```
    """
    return UnaryOp(UnaryOpType.Positive, e)

unpack ¤

unpack(e: IntoExpression) -> UnaryOp

Sequence unpacking operation.

Examples:

unpacked_expr = unpack(list_(litint(1), litint(2), litint(3)))
assert unpacked_expr.into_code() == "* [1, 2, 3]"
Source code in synt/expr/unary_op.py
def unpack(e: expr.IntoExpression) -> UnaryOp:
    r"""Sequence unpacking operation.

    Examples:
        ```python
        unpacked_expr = unpack(list_(litint(1), litint(2), litint(3)))
        assert unpacked_expr.into_code() == "* [1, 2, 3]"
        ```
    """
    return UnaryOp(UnaryOpType.Starred, e)

unpack_kv ¤

unpack_kv(e: IntoExpression) -> UnaryOp

K-V pair unpacking operation.

Examples:

unpacked_expr = unpack_kv(dict_(kv(litint(1), litstr('a'))))
assert unpacked_expr.into_code() == "** {1: 'a'}"
Source code in synt/expr/unary_op.py
def unpack_kv(e: expr.IntoExpression) -> UnaryOp:
    r"""K-V pair unpacking operation.

    Examples:
        ```python
        unpacked_expr = unpack_kv(dict_(kv(litint(1), litstr('a'))))
        assert unpacked_expr.into_code() == "** {1: 'a'}"
        ```
    """
    return UnaryOp(UnaryOpType.DoubleStarred, e)

yield_ ¤

yield_(e: Expression) -> UnaryOp

Yield operation.

Examples:

yield_expr = yield_(litint(10))
assert yield_expr.into_code() == "yield 10"
Source code in synt/expr/unary_op.py
def yield_(e: expr.Expression) -> UnaryOp:
    r"""Yield operation.

    Examples:
        ```python
        yield_expr = yield_(litint(10))
        assert yield_expr.into_code() == "yield 10"
        ```
    """
    return UnaryOp(UnaryOpType.Yield, e)

yield_from ¤

yield_from(e: Expression) -> UnaryOp

Yield from operation.

Examples:

yield_expr = yield_from(list_(litint(10), litint(42)))
assert yield_expr.into_code() == "yield from [10, 42]"
Source code in synt/expr/unary_op.py
def yield_from(e: expr.Expression) -> UnaryOp:
    r"""Yield from operation.

    Examples:
        ```python
        yield_expr = yield_from(list_(litint(10), litint(42)))
        assert yield_expr.into_code() == "yield from [10, 42]"
        ```
    """
    return UnaryOp(UnaryOpType.YieldFrom, e)

if_ ¤

Initialize a new branch statement.

Parameters:

Name Type Description Default
test IntoExpression

The expression to test.

required
References

Branch.

Source code in synt/stmt/branch.py
def if_(test: IntoExpression) -> BranchBuilder:
    r"""Initialize a new branch statement.

    Args:
        test: The expression to test.

    References:
        [`Branch`][synt.stmt.branch.Branch].
    """
    return Branch().elif_(test)

class_ ¤

class_(name: Identifier) -> ClassDefBuilder

Initialize a class without decorators.

Parameters:

Name Type Description Default
name Identifier

Class name.

required
Source code in synt/stmt/cls.py
def class_(name: Identifier) -> ClassDefBuilder:
    r"""Initialize a class without decorators.

    Args:
        name: Class name.
    """
    return ClassDefBuilder().class_(name)

async_def ¤

async_def(name: Identifier) -> FunctionDefBuilder

Initialize an async function definition.

Parameters:

Name Type Description Default
name Identifier

Function name.

required
Source code in synt/stmt/fn.py
def async_def(name: Identifier) -> FunctionDefBuilder:
    r"""Initialize an async function definition.

    Args:
        name: Function name.
    """
    return FunctionDefBuilder().async_def(name)

def_ ¤

Initialize a function definition.

Parameters:

Name Type Description Default
name Identifier

Function name.

required
Source code in synt/stmt/fn.py
def def_(name: Identifier) -> FunctionDefBuilder:
    r"""Initialize a function definition.

    Args:
        name: Function name.
    """
    return FunctionDefBuilder().def_(name)

kwarg ¤

kwarg(i: Identifier) -> FnArg

Initialize a keyword argument.

This is equivalent to FnArg(...).kwarg().

Examples:

va = kwarg(id_("foo")).ty(id_("tuple").expr()[id_("str"), id_("int")])
assert va.into_code() == "**foo: tuple[str, int]"
Source code in synt/stmt/fn.py
def kwarg(i: Identifier) -> FnArg:
    r"""Initialize a keyword argument.

    This is equivalent to `FnArg(...).kwarg()`.

    Examples:
        ```python
        va = kwarg(id_("foo")).ty(id_("tuple").expr()[id_("str"), id_("int")])
        assert va.into_code() == "**foo: tuple[str, int]"
        ```
    """
    return FnArg(i).kwarg()

vararg ¤

vararg(i: Identifier) -> FnArg

Initialize a variable argument.

This is equivalent to FnArg(...).vararg().

Examples:

va = vararg(id_("foo")).ty(id_("int"))
assert va.into_code() == "*foo: int"
Source code in synt/stmt/fn.py
def vararg(i: Identifier) -> FnArg:
    r"""Initialize a variable argument.

    This is equivalent to `FnArg(...).vararg()`.

    Examples:
        ```python
        va = vararg(id_("foo")).ty(id_("int"))
        assert va.into_code() == "*foo: int"
        ```
    """
    return FnArg(i).vararg()

try_ ¤

try_(*statement: Statement) -> Try

Initialize a try statement.

Parameters:

Name Type Description Default
statement Statement

The statements in the try block.

()
Source code in synt/stmt/try_catch.py
def try_(*statement: Statement) -> Try:
    r"""Initialize a `try` statement.

    Args:
        statement: The statements in the `try` block.
    """
    return Try(Block(*statement), [], None, None)

stmt ¤

assertion ¤

assert_ module-attribute ¤

assert_ = Assert

Alias Assert.

Assert ¤

Bases: Statement

The assert statement.

Examples:

assert_stmt = assert_(TRUE, litstr("Condition is true"))
assert assert_stmt.into_code() == "assert True, 'Condition is true'"
References

Assert.

Source code in synt/stmt/assertion.py
class Assert(Statement):
    r"""The `assert` statement.

    Examples:
        ```python
        assert_stmt = assert_(TRUE, litstr("Condition is true"))
        assert assert_stmt.into_code() == "assert True, 'Condition is true'"
        ```

    References:
        [`Assert`](https://docs.python.org/3/library/ast.html#ast.Assert).
    """

    test: Expression
    """The expression to assert."""
    msg: Expression | None
    """The assert message."""

    def __init__(self, test: IntoExpression, msg: IntoExpression | None = None):
        """Initialize the assertion.

        Args:
            test: The expression to assert.
            msg: The assert message.
        """
        self.test = test.into_expression()
        if msg:
            self.msg = msg.into_expression()
        else:
            self.msg = None

    def indented(self, indent_width: int, indent_atom: str) -> str:
        msg = f", {self.msg.into_code()}" if self.msg else ""
        return f"{indent_width * indent_atom}assert {self.test.into_code()}{msg}"
msg instance-attribute ¤
msg: Expression | None

The assert message.

test instance-attribute ¤
test: Expression = into_expression()

The expression to assert.

__init__ ¤
1
2
3
__init__(
    test: IntoExpression, msg: IntoExpression | None = None
)

Initialize the assertion.

Parameters:

Name Type Description Default
test IntoExpression

The expression to assert.

required
msg IntoExpression | None

The assert message.

None
Source code in synt/stmt/assertion.py
def __init__(self, test: IntoExpression, msg: IntoExpression | None = None):
    """Initialize the assertion.

    Args:
        test: The expression to assert.
        msg: The assert message.
    """
    self.test = test.into_expression()
    if msg:
        self.msg = msg.into_expression()
    else:
        self.msg = None
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/assertion.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    msg = f", {self.msg.into_code()}" if self.msg else ""
    return f"{indent_width * indent_atom}assert {self.test.into_code()}{msg}"

assign ¤

assign module-attribute ¤

assign = Assignment

Alias Assignment.

Assignment ¤

Bases: Statement

Assignment statement.

Examples:

1
2
3
4
5
6
ass = tup(id_("a"), id_("b")).assign(tup(litint(1), litstr("foo")))
assert ass.into_code() == "a, b = (1, 'foo')" # automatically unpack
ass = id_("a").expr().ty(id_("str")).assign(litstr("foo"))
assert ass.into_code() == "a: str = 'foo'" # explicitly typing
ass = id_("a").expr().ty(id_("str"))
assert ass.into_code() == "a: str" # only typing
References

Assign
AnnAssign
AugAssign.

Source code in synt/stmt/assign.py
class Assignment(Statement):
    r"""Assignment statement.

    Examples:
        ```python
        ass = tup(id_("a"), id_("b")).assign(tup(litint(1), litstr("foo")))
        assert ass.into_code() == "a, b = (1, 'foo')" # automatically unpack
        ass = id_("a").expr().ty(id_("str")).assign(litstr("foo"))
        assert ass.into_code() == "a: str = 'foo'" # explicitly typing
        ass = id_("a").expr().ty(id_("str"))
        assert ass.into_code() == "a: str" # only typing
        ```

    References:
        [`Assign`](https://docs.python.org/3/library/ast.html#ast.Assign)<br/>
        [`AnnAssign`](https://docs.python.org/3/library/ast.html#ast.AnnAssign)<br/>
        [`AugAssign`](https://docs.python.org/3/library/ast.html#ast.AugAssign).
    """

    target: Expression
    """Target of the assignment."""
    target_ty: Expression | None
    """The type of the target."""
    value: Expression | None
    """The value to be assigned."""

    def __init__(self, target: IntoExpression):
        """Initialize a new assignment statement.

        Args:
            target: The variable to be assigned to.
        """
        self.target = target.into_expression()
        self.target_ty = None
        self.value = None

    def type(self, ty: IntoExpression) -> Self:
        """Set the target's type.

        Args:
            ty: The type of the target variable.
        """
        self.target_ty = ty.into_expression()
        return self

    def assign(self, v: IntoExpression) -> Self:
        """Set the target's value.

        Args:
            v: The value of the assignment.
        """
        self.value = v.into_expression()
        return self

    def indented(self, indent_width: int, indent_atom: str) -> str:
        if is_tuple(self.target):  # implicit tuple, like `a, b = foo`.
            target = self.target.into_code_implicit()
        else:
            target = self.target.into_code()
        tty = f": {self.target_ty.into_code()}" if self.target_ty is not None else ""
        ass = f" = {self.value.into_code()}" if self.value is not None else ""
        return f"{indent_atom * indent_width}{target}{tty}{ass}"
target instance-attribute ¤
target: Expression = into_expression()

Target of the assignment.

target_ty instance-attribute ¤
target_ty: Expression | None = None

The type of the target.

value instance-attribute ¤
value: Expression | None = None

The value to be assigned.

__init__ ¤
__init__(target: IntoExpression)

Initialize a new assignment statement.

Parameters:

Name Type Description Default
target IntoExpression

The variable to be assigned to.

required
Source code in synt/stmt/assign.py
def __init__(self, target: IntoExpression):
    """Initialize a new assignment statement.

    Args:
        target: The variable to be assigned to.
    """
    self.target = target.into_expression()
    self.target_ty = None
    self.value = None
type ¤
type(ty: IntoExpression) -> Self

Set the target's type.

Parameters:

Name Type Description Default
ty IntoExpression

The type of the target variable.

required
Source code in synt/stmt/assign.py
def type(self, ty: IntoExpression) -> Self:
    """Set the target's type.

    Args:
        ty: The type of the target variable.
    """
    self.target_ty = ty.into_expression()
    return self
assign ¤
assign(v: IntoExpression) -> Self

Set the target's value.

Parameters:

Name Type Description Default
v IntoExpression

The value of the assignment.

required
Source code in synt/stmt/assign.py
def assign(self, v: IntoExpression) -> Self:
    """Set the target's value.

    Args:
        v: The value of the assignment.
    """
    self.value = v.into_expression()
    return self
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/assign.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    if is_tuple(self.target):  # implicit tuple, like `a, b = foo`.
        target = self.target.into_code_implicit()
    else:
        target = self.target.into_code()
    tty = f": {self.target_ty.into_code()}" if self.target_ty is not None else ""
    ass = f" = {self.value.into_code()}" if self.value is not None else ""
    return f"{indent_atom * indent_width}{target}{tty}{ass}"

block ¤

Block ¤

Bases: Statement

A Python code block.

Source code in synt/stmt/block.py
class Block(Statement):
    r"""A Python code block."""

    body: list[Statement]
    """Code lines in the block."""

    def __init__(self, *args: Statement):
        """Initialize a new code block.

        Args:
            args: code lines.
        """
        self.body = list(args)

    def indented(self, indent_width: int, indent_atom: str) -> str:
        return "\n".join(
            f"{line.indented(indent_width, indent_atom)}" for line in self.body
        )
body instance-attribute ¤
body: list[Statement] = list(args)

Code lines in the block.

__init__ ¤
__init__(*args: Statement)

Initialize a new code block.

Parameters:

Name Type Description Default
args Statement

code lines.

()
Source code in synt/stmt/block.py
def __init__(self, *args: Statement):
    """Initialize a new code block.

    Args:
        args: code lines.
    """
    self.body = list(args)
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/block.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    return "\n".join(
        f"{line.indented(indent_width, indent_atom)}" for line in self.body
    )

branch ¤

Branch ¤

Bases: Statement

The branch statement, aka if ... elif ... else.

Examples:

if_stmt = if_(id_("foo").expr().eq(litstr("bar"))).block(
              return_(TRUE)
          )
assert if_stmt.into_code() == "if foo == 'bar':\n    return True"
# if foo == 'bar'
#     return True

if_stmt = if_(id_("foo").expr().eq(litstr("bar"))).block(
              return_(TRUE)
          ).elif_(id_("foo").expr().is_not(NONE)).block(
              return_(FALSE)
          )
assert if_stmt.into_code() == '''if foo == 'bar':
    return True
elif foo is not None:
    return False'''
# if foo == 'bar':
#     return True
# elif foo is not None:
#     return False

if_stmt = if_(id_("foo").expr().eq(litstr("bar"))).block(
              return_(TRUE)
          ).elif_(id_("foo").expr().is_not(NONE)).block(
              return_(FALSE)
          ).else_(
              raise_(id_("ValueError").expr().call(litstr("Unexpected value")))
          )
assert if_stmt.into_code() == '''if foo == 'bar':
    return True
elif foo is not None:
    return False
else:
    raise ValueError('Unexpected value')'''
# if foo == 'bar':
#     return True
# elif foo is not None:
#     return False
# else:
#     raise ValueError('Unexpected value')
References

If.

Source code in synt/stmt/branch.py
class Branch(Statement):
    r"""The branch statement, aka `if ... elif ... else`.

    Examples:
        ```python
        if_stmt = if_(id_("foo").expr().eq(litstr("bar"))).block(
                      return_(TRUE)
                  )
        assert if_stmt.into_code() == "if foo == 'bar':\n    return True"
        # if foo == 'bar'
        #     return True

        if_stmt = if_(id_("foo").expr().eq(litstr("bar"))).block(
                      return_(TRUE)
                  ).elif_(id_("foo").expr().is_not(NONE)).block(
                      return_(FALSE)
                  )
        assert if_stmt.into_code() == '''if foo == 'bar':
            return True
        elif foo is not None:
            return False'''
        # if foo == 'bar':
        #     return True
        # elif foo is not None:
        #     return False

        if_stmt = if_(id_("foo").expr().eq(litstr("bar"))).block(
                      return_(TRUE)
                  ).elif_(id_("foo").expr().is_not(NONE)).block(
                      return_(FALSE)
                  ).else_(
                      raise_(id_("ValueError").expr().call(litstr("Unexpected value")))
                  )
        assert if_stmt.into_code() == '''if foo == 'bar':
            return True
        elif foo is not None:
            return False
        else:
            raise ValueError('Unexpected value')'''
        # if foo == 'bar':
        #     return True
        # elif foo is not None:
        #     return False
        # else:
        #     raise ValueError('Unexpected value')
        ```

    References:
        [`If`](https://docs.python.org/3/library/ast.html#ast.ImportFrom).
    """

    tests: list[tuple[Expression, Block]]
    """Branches of the statement, including `if` and `elif`."""
    fallback: Block | None
    """Fallback branch, aka `else`."""

    def __init__(self) -> None:
        """Initialize a new empty branch statement.

        **DO NOT USE THIS IN YOUR CODE!**
        """
        self.tests = []
        self.fallback = None

    def elif_(self, test: IntoExpression) -> BranchBuilder:
        """Create a new branch.

        Args:
            test: Expression to test.
        """
        return BranchBuilder(self, test)

    def else_(self, *statements: Statement) -> Self:
        """Add a fallback branch.

        Args:
            statements: List of statements.
        """
        self.fallback = Block(*statements)
        return self

    def indented(self, indent_width: int, indent_atom: str) -> str:
        if len(self.tests) == 0:
            raise ValueError("Empty branches, at least one test should be added.")
        indent = indent_atom * indent_width
        if_item = self.tests[0]
        if_text = f"{indent}if {if_item[0].into_code()}:\n{if_item[1].indented(indent_width + 1, indent_atom)}"
        if len(self.tests) > 1:
            elif_item = self.tests[1:]
            elif_text = "\n" + "\n".join(
                f"{indent}elif {x[0].into_code()}:\n{x[1].indented(indent_width + 1, indent_atom)}"
                for x in elif_item
            )
        else:
            elif_text = ""
        if self.fallback is not None:
            else_text = f"\n{indent}else:\n{self.fallback.indented(indent_width + 1, indent_atom)}"
        else:
            else_text = ""
        return if_text + elif_text + else_text
tests instance-attribute ¤
tests: list[tuple[Expression, Block]] = []

Branches of the statement, including if and elif.

fallback instance-attribute ¤
fallback: Block | None = None

Fallback branch, aka else.

__init__ ¤
__init__() -> None

Initialize a new empty branch statement.

DO NOT USE THIS IN YOUR CODE!

Source code in synt/stmt/branch.py
def __init__(self) -> None:
    """Initialize a new empty branch statement.

    **DO NOT USE THIS IN YOUR CODE!**
    """
    self.tests = []
    self.fallback = None
elif_ ¤

Create a new branch.

Parameters:

Name Type Description Default
test IntoExpression

Expression to test.

required
Source code in synt/stmt/branch.py
def elif_(self, test: IntoExpression) -> BranchBuilder:
    """Create a new branch.

    Args:
        test: Expression to test.
    """
    return BranchBuilder(self, test)
else_ ¤
else_(*statements: Statement) -> Self

Add a fallback branch.

Parameters:

Name Type Description Default
statements Statement

List of statements.

()
Source code in synt/stmt/branch.py
def else_(self, *statements: Statement) -> Self:
    """Add a fallback branch.

    Args:
        statements: List of statements.
    """
    self.fallback = Block(*statements)
    return self
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/branch.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    if len(self.tests) == 0:
        raise ValueError("Empty branches, at least one test should be added.")
    indent = indent_atom * indent_width
    if_item = self.tests[0]
    if_text = f"{indent}if {if_item[0].into_code()}:\n{if_item[1].indented(indent_width + 1, indent_atom)}"
    if len(self.tests) > 1:
        elif_item = self.tests[1:]
        elif_text = "\n" + "\n".join(
            f"{indent}elif {x[0].into_code()}:\n{x[1].indented(indent_width + 1, indent_atom)}"
            for x in elif_item
        )
    else:
        elif_text = ""
    if self.fallback is not None:
        else_text = f"\n{indent}else:\n{self.fallback.indented(indent_width + 1, indent_atom)}"
    else:
        else_text = ""
    return if_text + elif_text + else_text

BranchBuilder ¤

A single branch builder for the branch statement.

Source code in synt/stmt/branch.py
class BranchBuilder:
    r"""A single branch builder for the branch statement."""

    parent: Branch
    """Parent node."""
    test: Expression
    """The expression to test."""

    def __init__(self, parent: Branch, test: IntoExpression):
        """Initialize a branch builder.

        Args:
            parent: The parent node.
            test: The expression to test.
        """
        self.parent = parent
        self.test = test.into_expression()

    def block(self, *statements: Statement) -> Branch:
        """Append a block to the branch.

        Args:
            statements: Statements to include in the block.
        """
        block = Block(*statements)
        self.parent.tests.append((self.test, block))
        return self.parent
parent instance-attribute ¤
parent: Branch = parent

Parent node.

test instance-attribute ¤
test: Expression = into_expression()

The expression to test.

__init__ ¤
__init__(parent: Branch, test: IntoExpression)

Initialize a branch builder.

Parameters:

Name Type Description Default
parent Branch

The parent node.

required
test IntoExpression

The expression to test.

required
Source code in synt/stmt/branch.py
def __init__(self, parent: Branch, test: IntoExpression):
    """Initialize a branch builder.

    Args:
        parent: The parent node.
        test: The expression to test.
    """
    self.parent = parent
    self.test = test.into_expression()
block ¤
block(*statements: Statement) -> Branch

Append a block to the branch.

Parameters:

Name Type Description Default
statements Statement

Statements to include in the block.

()
Source code in synt/stmt/branch.py
def block(self, *statements: Statement) -> Branch:
    """Append a block to the branch.

    Args:
        statements: Statements to include in the block.
    """
    block = Block(*statements)
    self.parent.tests.append((self.test, block))
    return self.parent

if_ ¤

Initialize a new branch statement.

Parameters:

Name Type Description Default
test IntoExpression

The expression to test.

required
References

Branch.

Source code in synt/stmt/branch.py
def if_(test: IntoExpression) -> BranchBuilder:
    r"""Initialize a new branch statement.

    Args:
        test: The expression to test.

    References:
        [`Branch`][synt.stmt.branch.Branch].
    """
    return Branch().elif_(test)

cls ¤

ClassDef ¤

Bases: Statement

Class definition.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Examples:
    ```python
    cls = (
        dec(id_("foo"))
        .class_(id_("Bar"))[id_("T")](metaclass=id_("ABCMeta"))
        .block(
            dec(id_("abstractmethod"))
            .def_(id_("baz"))(id_("self"), arg(id_("a"), id_("T"))).returns(id_("str"))
            .block(
                return_(fstring("Bar(", fnode(id_("a")), ").baz"))
            )
        )
    )
    assert cls.into_code() == '''@foo

class BarT: @abstractmethod def baz(self, a: T) -> str: return f"Bar({a}).baz"'''

1
2
3
4
5
6
7
8
9
    # @foo
    # class Bar[T](metaclass=ABCMeta):
    #     @abstractmethod
    #     def baz(self, a: T) -> str:
    #         return f"Bar({a}).baz"
    ```

References:
    [`ClassDef`](https://docs.python.org/3/library/ast.html#ast.ClassDef).
Source code in synt/stmt/cls.py
class ClassDef(Statement):
    r"""Class definition.

        Examples:
            ```python
            cls = (
                dec(id_("foo"))
                .class_(id_("Bar"))[id_("T")](metaclass=id_("ABCMeta"))
                .block(
                    dec(id_("abstractmethod"))
                    .def_(id_("baz"))(id_("self"), arg(id_("a"), id_("T"))).returns(id_("str"))
                    .block(
                        return_(fstring("Bar(", fnode(id_("a")), ").baz"))
                    )
                )
            )
            assert cls.into_code() == '''@foo
    class Bar[T](metaclass=ABCMeta):
        @abstractmethod
        def baz(self, a: T) -> str:
            return f"Bar({a}).baz"'''

            # @foo
            # class Bar[T](metaclass=ABCMeta):
            #     @abstractmethod
            #     def baz(self, a: T) -> str:
            #         return f"Bar({a}).baz"
            ```

        References:
            [`ClassDef`](https://docs.python.org/3/library/ast.html#ast.ClassDef).
    """

    decorators: list[Expression]
    """Decorators."""
    name: Identifier
    """Class name."""
    type_params: list[TypeParam]
    """Type parameters."""
    cargs: list[Expression]
    """Class arguments.

    E.g., base classes.
    """
    ckwargs: list[tuple[Identifier, Expression]]
    """Class keyword arguments.

    E.g., meta classes.
    """
    body: Block
    """Function body."""

    def __init__(
        self,
        decorators: list[Expression],
        type_params: list[TypeParam],
        name: Identifier,
        cargs: list[Expression],
        ckwargs: list[tuple[Identifier, Expression]],
        body: Block,
    ):
        """Initialize a function definition.

        **DO NOT USE THIS IN YOUR CODE!**
        """
        self.decorators = decorators
        self.type_params = type_params
        self.cargs = cargs
        self.ckwargs = ckwargs
        self.name = name
        self.body = body

    def indented(self, indent_width: int, indent_atom: str) -> str:
        indent = indent_width * indent_atom
        decorators = "".join(f"{indent}@{t.into_code()}\n" for t in self.decorators)
        type_param = (
            ""
            if not self.type_params
            else f"[{', '.join(x.into_code() for x in self.type_params)}]"
        )
        args_l: list[str] = []
        args_l.extend(x.into_code() for x in self.cargs)
        args_l.extend(f"{x[0].into_code()}={x[1].into_code()}" for x in self.ckwargs)
        args = f"({', '.join(args_l)})" if args_l else ""
        body = self.body.indented(indent_width + 1, indent_atom)
        return f"{decorators}{indent}class {self.name.into_code()}{type_param}{args}:\n{body}"
decorators instance-attribute ¤
decorators: list[Expression] = decorators

Decorators.

type_params instance-attribute ¤
type_params: list[TypeParam] = type_params

Type parameters.

cargs instance-attribute ¤

Class arguments.

E.g., base classes.

ckwargs instance-attribute ¤

Class keyword arguments.

E.g., meta classes.

name instance-attribute ¤
name: Identifier = name

Class name.

body instance-attribute ¤
body: Block = body

Function body.

__init__ ¤
1
2
3
4
5
6
7
8
__init__(
    decorators: list[Expression],
    type_params: list[TypeParam],
    name: Identifier,
    cargs: list[Expression],
    ckwargs: list[tuple[Identifier, Expression]],
    body: Block,
)

Initialize a function definition.

DO NOT USE THIS IN YOUR CODE!

Source code in synt/stmt/cls.py
def __init__(
    self,
    decorators: list[Expression],
    type_params: list[TypeParam],
    name: Identifier,
    cargs: list[Expression],
    ckwargs: list[tuple[Identifier, Expression]],
    body: Block,
):
    """Initialize a function definition.

    **DO NOT USE THIS IN YOUR CODE!**
    """
    self.decorators = decorators
    self.type_params = type_params
    self.cargs = cargs
    self.ckwargs = ckwargs
    self.name = name
    self.body = body
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/cls.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    indent = indent_width * indent_atom
    decorators = "".join(f"{indent}@{t.into_code()}\n" for t in self.decorators)
    type_param = (
        ""
        if not self.type_params
        else f"[{', '.join(x.into_code() for x in self.type_params)}]"
    )
    args_l: list[str] = []
    args_l.extend(x.into_code() for x in self.cargs)
    args_l.extend(f"{x[0].into_code()}={x[1].into_code()}" for x in self.ckwargs)
    args = f"({', '.join(args_l)})" if args_l else ""
    body = self.body.indented(indent_width + 1, indent_atom)
    return f"{decorators}{indent}class {self.name.into_code()}{type_param}{args}:\n{body}"

ClassDefBuilder ¤

Class definition builder.

References

ClassDef.

Source code in synt/stmt/cls.py
class ClassDefBuilder:
    r"""Class definition builder.

    References:
        [`ClassDef`][synt.stmt.cls.ClassDef].
    """

    decorators: list[Expression]
    """Decorators."""
    name: Identifier | None
    """Class name."""
    type_params: list[TypeParam]
    """Type parameters."""
    cargs: list[Expression]
    """Class arguments.

    E.g., base classes.
    """
    ckwargs: list[tuple[Identifier, Expression]]
    """Class keyword arguments.

    E.g., meta classes.
    """

    def __init__(self) -> None:
        """Initialize an empty builder."""
        self.decorators = []
        self.name = None
        self.type_params = []
        self.cargs = []
        self.ckwargs = []

    def decorator(self, decorator: IntoExpression) -> Self:
        """Append a decorator.

        Args:
            decorator: Decorator to append.
        """
        self.decorators.append(decorator.into_expression())
        return self

    def dec(self, decorator: IntoExpression) -> Self:
        """Alias [`decorator`][synt.stmt.cls.ClassDefBuilder.decorator]."""
        return self.decorator(decorator)

    def class_(self, name: Identifier) -> Self:
        """Initialize a class.

        Args:
            name: Class name.
        """
        self.name = name
        return self

    def type_param(self, *args: TypeParam | Identifier) -> Self:
        """Add generic type parameters.

        Args:
            *args: Type parameters to add.
        """
        from synt.tokens.ident import Identifier

        self.type_params = [
            TypeVar(x) if isinstance(x, Identifier) else x for x in args
        ]
        return self

    def ty(self, *args: TypeParam | Identifier) -> Self:
        """Alias [`type_param`][synt.stmt.cls.ClassDefBuilder.type_param]."""
        return self.type_param(*args)

    def __getitem__(
        self, items: tuple[TypeParam | Identifier, ...] | TypeParam | Identifier
    ) -> Self:
        """Alias [`type_param`][synt.stmt.cls.ClassDefBuilder.type_param]."""
        if isinstance(items, tuple):
            return self.type_param(*items)
        else:
            return self.type_param(items)

    def arg(
        self,
        *args: IntoExpression | tuple[Identifier, IntoExpression],
        **kwargs: IntoExpression,
    ) -> Self:
        """Add arguments for the class.

        Args:
            *args: Arguments to add.
            **kwargs: Keyword arguments to add with their default values.
        """
        from synt.tokens.ident import Identifier

        self.cargs = []
        self.ckwargs = []
        for a in args:
            if isinstance(a, tuple):
                self.ckwargs.append((a[0], a[1].into_expression()))
            else:
                self.cargs.append(a.into_expression())
        for k, v in kwargs.items():
            self.ckwargs.append((Identifier(k), v.into_expression()))
        return self

    def __call__(
        self,
        *args: IntoExpression | tuple[Identifier, IntoExpression],
        **kwargs: IntoExpression,
    ) -> Self:
        """Alias [`arg`][synt.stmt.cls.ClassDefBuilder.arg]."""
        return self.arg(*args, **kwargs)

    def block(self, *statements: Statement) -> ClassDef:
        """Set the block of the class, and build it.

        Args:
            *statements: Statements to include in the class body.

        Raises:
            ValueError: If the required fields (`[name,]`) are not set.
        """
        err_fields = []
        if self.name is None:
            err_fields.append("name")

        if err_fields:
            raise ValueError(
                f"Missing required fields: {', '.join(f'`{t}`' for t in err_fields)}"
            )

        return ClassDef(
            decorators=self.decorators,
            type_params=self.type_params,
            cargs=self.cargs,
            ckwargs=self.ckwargs,
            name=self.name,  # type:ignore[arg-type]
            body=Block(*statements),
        )
decorators instance-attribute ¤
decorators: list[Expression] = []

Decorators.

name instance-attribute ¤
name: Identifier | None = None

Class name.

type_params instance-attribute ¤
type_params: list[TypeParam] = []

Type parameters.

cargs instance-attribute ¤
cargs: list[Expression] = []

Class arguments.

E.g., base classes.

ckwargs instance-attribute ¤
ckwargs: list[tuple[Identifier, Expression]] = []

Class keyword arguments.

E.g., meta classes.

__init__ ¤
__init__() -> None

Initialize an empty builder.

Source code in synt/stmt/cls.py
def __init__(self) -> None:
    """Initialize an empty builder."""
    self.decorators = []
    self.name = None
    self.type_params = []
    self.cargs = []
    self.ckwargs = []
decorator ¤
decorator(decorator: IntoExpression) -> Self

Append a decorator.

Parameters:

Name Type Description Default
decorator IntoExpression

Decorator to append.

required
Source code in synt/stmt/cls.py
def decorator(self, decorator: IntoExpression) -> Self:
    """Append a decorator.

    Args:
        decorator: Decorator to append.
    """
    self.decorators.append(decorator.into_expression())
    return self
dec ¤
dec(decorator: IntoExpression) -> Self

Alias decorator.

Source code in synt/stmt/cls.py
def dec(self, decorator: IntoExpression) -> Self:
    """Alias [`decorator`][synt.stmt.cls.ClassDefBuilder.decorator]."""
    return self.decorator(decorator)
class_ ¤
class_(name: Identifier) -> Self

Initialize a class.

Parameters:

Name Type Description Default
name Identifier

Class name.

required
Source code in synt/stmt/cls.py
def class_(self, name: Identifier) -> Self:
    """Initialize a class.

    Args:
        name: Class name.
    """
    self.name = name
    return self
type_param ¤
type_param(*args: TypeParam | Identifier) -> Self

Add generic type parameters.

Parameters:

Name Type Description Default
*args TypeParam | Identifier

Type parameters to add.

()
Source code in synt/stmt/cls.py
def type_param(self, *args: TypeParam | Identifier) -> Self:
    """Add generic type parameters.

    Args:
        *args: Type parameters to add.
    """
    from synt.tokens.ident import Identifier

    self.type_params = [
        TypeVar(x) if isinstance(x, Identifier) else x for x in args
    ]
    return self
ty ¤
ty(*args: TypeParam | Identifier) -> Self

Alias type_param.

Source code in synt/stmt/cls.py
def ty(self, *args: TypeParam | Identifier) -> Self:
    """Alias [`type_param`][synt.stmt.cls.ClassDefBuilder.type_param]."""
    return self.type_param(*args)
__getitem__ ¤
1
2
3
4
5
6
7
__getitem__(
    items: (
        tuple[TypeParam | Identifier, ...]
        | TypeParam
        | Identifier
    )
) -> Self

Alias type_param.

Source code in synt/stmt/cls.py
def __getitem__(
    self, items: tuple[TypeParam | Identifier, ...] | TypeParam | Identifier
) -> Self:
    """Alias [`type_param`][synt.stmt.cls.ClassDefBuilder.type_param]."""
    if isinstance(items, tuple):
        return self.type_param(*items)
    else:
        return self.type_param(items)
arg ¤

Add arguments for the class.

Parameters:

Name Type Description Default
*args IntoExpression | tuple[Identifier, IntoExpression]

Arguments to add.

()
**kwargs IntoExpression

Keyword arguments to add with their default values.

{}
Source code in synt/stmt/cls.py
def arg(
    self,
    *args: IntoExpression | tuple[Identifier, IntoExpression],
    **kwargs: IntoExpression,
) -> Self:
    """Add arguments for the class.

    Args:
        *args: Arguments to add.
        **kwargs: Keyword arguments to add with their default values.
    """
    from synt.tokens.ident import Identifier

    self.cargs = []
    self.ckwargs = []
    for a in args:
        if isinstance(a, tuple):
            self.ckwargs.append((a[0], a[1].into_expression()))
        else:
            self.cargs.append(a.into_expression())
    for k, v in kwargs.items():
        self.ckwargs.append((Identifier(k), v.into_expression()))
    return self
__call__ ¤
1
2
3
4
5
__call__(
    *args: IntoExpression
    | tuple[Identifier, IntoExpression],
    **kwargs: IntoExpression
) -> Self

Alias arg.

Source code in synt/stmt/cls.py
def __call__(
    self,
    *args: IntoExpression | tuple[Identifier, IntoExpression],
    **kwargs: IntoExpression,
) -> Self:
    """Alias [`arg`][synt.stmt.cls.ClassDefBuilder.arg]."""
    return self.arg(*args, **kwargs)
block ¤
block(*statements: Statement) -> ClassDef

Set the block of the class, and build it.

Parameters:

Name Type Description Default
*statements Statement

Statements to include in the class body.

()

Raises:

Type Description
ValueError

If the required fields ([name,]) are not set.

Source code in synt/stmt/cls.py
def block(self, *statements: Statement) -> ClassDef:
    """Set the block of the class, and build it.

    Args:
        *statements: Statements to include in the class body.

    Raises:
        ValueError: If the required fields (`[name,]`) are not set.
    """
    err_fields = []
    if self.name is None:
        err_fields.append("name")

    if err_fields:
        raise ValueError(
            f"Missing required fields: {', '.join(f'`{t}`' for t in err_fields)}"
        )

    return ClassDef(
        decorators=self.decorators,
        type_params=self.type_params,
        cargs=self.cargs,
        ckwargs=self.ckwargs,
        name=self.name,  # type:ignore[arg-type]
        body=Block(*statements),
    )

class_ ¤

class_(name: Identifier) -> ClassDefBuilder

Initialize a class without decorators.

Parameters:

Name Type Description Default
name Identifier

Class name.

required
Source code in synt/stmt/cls.py
def class_(name: Identifier) -> ClassDefBuilder:
    r"""Initialize a class without decorators.

    Args:
        name: Class name.
    """
    return ClassDefBuilder().class_(name)

context ¤

with_item module-attribute ¤

with_item = WithItem

Alias WithItem.

with_ module-attribute ¤

with_ = WithBuilder

Alias WithBuilder.

WithItem ¤

Bases: IntoCode

An item of the with statement.

References

withitem.

Source code in synt/stmt/context.py
class WithItem(IntoCode):
    """An item of the `with` statement.

    References:
        [`withitem`](https://docs.python.org/3/library/ast.html#ast.withitem).
    """

    context: Expression
    """The context expression."""
    asname: Expression | None
    """The alias for the context expression.

    Notes:
        ```python
        with a as b:
            ...
        ```
        Consider the above example, the context returned by `a` is assigned to `b`.
        Hence, `b`, the syntax node, must be an assignable object, that is,
        a `tuple`, `list`, or a single `Identifier`.
    """

    def __init__(self, context: IntoExpression):
        """Initialize a new `with` item.

        Args:
            context: The context expression.
        """
        self.context = context.into_expression()
        self.asname = None

    def as_(self, asname: IntoExpression) -> Self:
        """Set the alias.

        Args:
            asname: The alias for the context expression.
        """
        self.asname = asname.into_expression()
        return self

    def into_code(self) -> str:
        asname_text = (
            f" as {self.asname.into_code()}" if self.asname is not None else ""
        )
        return f"{self.context.into_code()}{asname_text}"
context instance-attribute ¤
context: Expression = into_expression()

The context expression.

asname instance-attribute ¤
asname: Expression | None = None

The alias for the context expression.

Notes

with a as b:
    ...
Consider the above example, the context returned by a is assigned to b. Hence, b, the syntax node, must be an assignable object, that is, a tuple, list, or a single Identifier.

__init__ ¤
__init__(context: IntoExpression)

Initialize a new with item.

Parameters:

Name Type Description Default
context IntoExpression

The context expression.

required
Source code in synt/stmt/context.py
def __init__(self, context: IntoExpression):
    """Initialize a new `with` item.

    Args:
        context: The context expression.
    """
    self.context = context.into_expression()
    self.asname = None
as_ ¤
as_(asname: IntoExpression) -> Self

Set the alias.

Parameters:

Name Type Description Default
asname IntoExpression

The alias for the context expression.

required
Source code in synt/stmt/context.py
def as_(self, asname: IntoExpression) -> Self:
    """Set the alias.

    Args:
        asname: The alias for the context expression.
    """
    self.asname = asname.into_expression()
    return self
into_code ¤
into_code() -> str
Source code in synt/stmt/context.py
def into_code(self) -> str:
    asname_text = (
        f" as {self.asname.into_code()}" if self.asname is not None else ""
    )
    return f"{self.context.into_code()}{asname_text}"

With ¤

Bases: Statement

The with statement.

Examples:

```python with_stmt = with_(id_("a"), (id_("b"), id_("b2")), with_item(id_("c")).as_(id_("c2"))).block( PASS ) assert with_stmt.into_code() == "with a, b as b2, c as c2:

pass" ```

References: With.

Source code in synt/stmt/context.py
class With(Statement):
    """The `with` statement.

    Examples:
        ```python
        with_stmt = with_(id_("a"), (id_("b"), id_("b2")), with_item(id_("c")).as_(id_("c2"))).block(
                        PASS
                    )
        assert with_stmt.into_code() == "with a, b as b2, c as c2:\n    pass"
        ```

    References:
        [`With`](https://docs.python.org/3/library/ast.html#ast.With).
    """

    items: list[WithItem]
    """`with` items."""
    body: Block
    """Statement block."""

    def __init__(self, items: list[WithItem], body: Block):
        """Initialize a `with` statement.

        **DO NOT USE THIS IN YOUR CODE!**

        Args:
            items: `with` items.
            body: Statement block.

        Raises:
            ValueError: If `items` is empty.
        """
        if len(items) == 0:
            raise ValueError("At least one `with` item is required.")
        self.items = items
        self.body = body

    def indented(self, indent_width: int, indent_atom: str) -> str:
        return (
            f"{indent_atom * indent_width}with {', '.join(x.into_code() for x in self.items)}:\n"
            f"{self.body.indented(indent_width + 1, indent_atom)}"
        )
items instance-attribute ¤
items: list[WithItem] = items

with items.

body instance-attribute ¤
body: Block = body

Statement block.

__init__ ¤
__init__(items: list[WithItem], body: Block)

Initialize a with statement.

DO NOT USE THIS IN YOUR CODE!

Parameters:

Name Type Description Default
items list[WithItem]

with items.

required
body Block

Statement block.

required

Raises:

Type Description
ValueError

If items is empty.

Source code in synt/stmt/context.py
def __init__(self, items: list[WithItem], body: Block):
    """Initialize a `with` statement.

    **DO NOT USE THIS IN YOUR CODE!**

    Args:
        items: `with` items.
        body: Statement block.

    Raises:
        ValueError: If `items` is empty.
    """
    if len(items) == 0:
        raise ValueError("At least one `with` item is required.")
    self.items = items
    self.body = body
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/context.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    return (
        f"{indent_atom * indent_width}with {', '.join(x.into_code() for x in self.items)}:\n"
        f"{self.body.indented(indent_width + 1, indent_atom)}"
    )

WithBuilder ¤

The builder for With.

Source code in synt/stmt/context.py
class WithBuilder:
    """The builder for [`With`][synt.stmt.context.With]."""

    items: list[WithItem]
    """`with` items."""

    def __init__(
        self, *items: WithItem | IntoExpression | tuple[IntoExpression, IntoExpression]
    ):
        """Initialize a `with` statement.

        The `items`'s item could be either `WithItem` object, an expression-like or a tuple:
        - `WithItem`: Save as-is.
        - Expression-like: Convert into a `WithItem` without any alias.
        - `tuple[IntoExpression, IntoExpression]`: The first element is the context, and the second is the alias.

        Args:
            items: `with` items.

        Raises:
            ValueError: If `items` is empty.
        """
        if len(items) == 0:
            raise ValueError("At least one `with` item is required.")
        self.items = []
        for item in items:
            if isinstance(item, tuple):
                self.items.append(
                    WithItem(item[0].into_expression()).as_(item[1].into_expression())
                )
            elif isinstance(item, WithItem):
                self.items.append(item)
            else:
                self.items.append(WithItem(item.into_expression()))

    def block(self, *statements: Statement) -> With:
        """Set the code block.

        Args:
            statements: block statements.
        """
        return With(self.items, Block(*statements))
items instance-attribute ¤
items: list[WithItem] = []

with items.

__init__ ¤

Initialize a with statement.

The items's item could be either WithItem object, an expression-like or a tuple: - WithItem: Save as-is. - Expression-like: Convert into a WithItem without any alias. - tuple[IntoExpression, IntoExpression]: The first element is the context, and the second is the alias.

Parameters:

Name Type Description Default
items WithItem | IntoExpression | tuple[IntoExpression, IntoExpression]

with items.

()

Raises:

Type Description
ValueError

If items is empty.

Source code in synt/stmt/context.py
def __init__(
    self, *items: WithItem | IntoExpression | tuple[IntoExpression, IntoExpression]
):
    """Initialize a `with` statement.

    The `items`'s item could be either `WithItem` object, an expression-like or a tuple:
    - `WithItem`: Save as-is.
    - Expression-like: Convert into a `WithItem` without any alias.
    - `tuple[IntoExpression, IntoExpression]`: The first element is the context, and the second is the alias.

    Args:
        items: `with` items.

    Raises:
        ValueError: If `items` is empty.
    """
    if len(items) == 0:
        raise ValueError("At least one `with` item is required.")
    self.items = []
    for item in items:
        if isinstance(item, tuple):
            self.items.append(
                WithItem(item[0].into_expression()).as_(item[1].into_expression())
            )
        elif isinstance(item, WithItem):
            self.items.append(item)
        else:
            self.items.append(WithItem(item.into_expression()))
block ¤
block(*statements: Statement) -> With

Set the code block.

Parameters:

Name Type Description Default
statements Statement

block statements.

()
Source code in synt/stmt/context.py
def block(self, *statements: Statement) -> With:
    """Set the code block.

    Args:
        statements: block statements.
    """
    return With(self.items, Block(*statements))

decorator ¤

dec module-attribute ¤

DecoratorGroup ¤

A group of decorators.

Source code in synt/stmt/decorator.py
class DecoratorGroup:
    r"""A group of decorators."""

    decorators: list[Expression]
    """Decorators."""

    def __init__(self, decorator: IntoExpression):
        """Initialize a decorator and create a new group.

        Args:
            decorator: The decorator to add.
        """
        self.decorators = [decorator.into_expression()]

    def dec(self, decorator: IntoExpression) -> Self:
        """Append a new decorator.

        Args:
            decorator: The decorator to add.
        """
        self.decorators.append(decorator.into_expression())
        return self

    def class_(self, name: Identifier) -> ClassDefBuilder:
        """Initialize a class with the decorators.

        Args:
            name: The name of the class.
        """
        cls = ClassDefBuilder()
        cls.decorators = self.decorators
        return cls.class_(name)

    def def_(self, name: Identifier) -> FunctionDefBuilder:
        """Initialize a function with the decorators.

        Args:
            name: The name of the function.
        """
        fn = FunctionDefBuilder()
        fn.decorators = self.decorators
        return fn.def_(name)

    def async_def(self, name: Identifier) -> FunctionDefBuilder:
        """Initialize an async function with the decorators.

        Args:
            name: The name of the function.
        """
        return self.def_(name).async_()
decorators instance-attribute ¤
decorators: list[Expression] = [into_expression()]

Decorators.

__init__ ¤
__init__(decorator: IntoExpression)

Initialize a decorator and create a new group.

Parameters:

Name Type Description Default
decorator IntoExpression

The decorator to add.

required
Source code in synt/stmt/decorator.py
def __init__(self, decorator: IntoExpression):
    """Initialize a decorator and create a new group.

    Args:
        decorator: The decorator to add.
    """
    self.decorators = [decorator.into_expression()]
dec ¤
dec(decorator: IntoExpression) -> Self

Append a new decorator.

Parameters:

Name Type Description Default
decorator IntoExpression

The decorator to add.

required
Source code in synt/stmt/decorator.py
def dec(self, decorator: IntoExpression) -> Self:
    """Append a new decorator.

    Args:
        decorator: The decorator to add.
    """
    self.decorators.append(decorator.into_expression())
    return self
class_ ¤
class_(name: Identifier) -> ClassDefBuilder

Initialize a class with the decorators.

Parameters:

Name Type Description Default
name Identifier

The name of the class.

required
Source code in synt/stmt/decorator.py
def class_(self, name: Identifier) -> ClassDefBuilder:
    """Initialize a class with the decorators.

    Args:
        name: The name of the class.
    """
    cls = ClassDefBuilder()
    cls.decorators = self.decorators
    return cls.class_(name)
def_ ¤

Initialize a function with the decorators.

Parameters:

Name Type Description Default
name Identifier

The name of the function.

required
Source code in synt/stmt/decorator.py
def def_(self, name: Identifier) -> FunctionDefBuilder:
    """Initialize a function with the decorators.

    Args:
        name: The name of the function.
    """
    fn = FunctionDefBuilder()
    fn.decorators = self.decorators
    return fn.def_(name)
async_def ¤
async_def(name: Identifier) -> FunctionDefBuilder

Initialize an async function with the decorators.

Parameters:

Name Type Description Default
name Identifier

The name of the function.

required
Source code in synt/stmt/decorator.py
def async_def(self, name: Identifier) -> FunctionDefBuilder:
    """Initialize an async function with the decorators.

    Args:
        name: The name of the function.
    """
    return self.def_(name).async_()

delete ¤

del_ module-attribute ¤

del_ = Delete

Alias Delete.

Delete ¤

Bases: Statement

The del statement.

Examples:

d = del_(id_("foo").expr().attr("bar"))
assert d.into_code() == "del foo.bar"
References

Delete.

Source code in synt/stmt/delete.py
class Delete(Statement):
    r"""The `del` statement.

    Examples:
        ```python
        d = del_(id_("foo").expr().attr("bar"))
        assert d.into_code() == "del foo.bar"
        ```

    References:
        [`Delete`](https://docs.python.org/3/library/ast.html#ast.Delete).
    """

    target: Expression
    """The expression to be deleted."""

    def __init__(self, target: IntoExpression):
        """Initialize the delete statement.

        Args:
            target: The expression to be deleted.
        """
        self.target = target.into_expression()

    def indented(self, indent_width: int, indent_atom: str) -> str:
        return f"{indent_atom * indent_width}del {self.target.into_code()}"
target instance-attribute ¤
target: Expression = into_expression()

The expression to be deleted.

__init__ ¤
__init__(target: IntoExpression)

Initialize the delete statement.

Parameters:

Name Type Description Default
target IntoExpression

The expression to be deleted.

required
Source code in synt/stmt/delete.py
def __init__(self, target: IntoExpression):
    """Initialize the delete statement.

    Args:
        target: The expression to be deleted.
    """
    self.target = target.into_expression()
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/delete.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    return f"{indent_atom * indent_width}del {self.target.into_code()}"

expression ¤

stmt module-attribute ¤

Alias ExprStatement.

ExprStatement ¤

Bases: Statement

A statement that only contains a single expression.

Examples:

stmt = id_("print").expr().call(litstr("Hello world!")).stmt()
assert stmt.into_code() == "print('Hello world!')"
Source code in synt/stmt/expression.py
class ExprStatement(Statement):
    """A statement that only contains a single expression.

    Examples:
        ```python
        stmt = id_("print").expr().call(litstr("Hello world!")).stmt()
        assert stmt.into_code() == "print('Hello world!')"
        ```
    """

    expr: Expression
    """Inner expression."""

    def __init__(self, expr: IntoExpression):
        """Initialize a nwe statement.

        Args:
            expr: Inner expression.
        """
        self.expr = expr.into_expression()

    def indented(self, indent_width: int, indent_atom: str) -> str:
        return f"{indent_atom * indent_width}{self.expr.into_code()}"
expr instance-attribute ¤
expr: Expression = into_expression()

Inner expression.

__init__ ¤
__init__(expr: IntoExpression)

Initialize a nwe statement.

Parameters:

Name Type Description Default
expr IntoExpression

Inner expression.

required
Source code in synt/stmt/expression.py
def __init__(self, expr: IntoExpression):
    """Initialize a nwe statement.

    Args:
        expr: Inner expression.
    """
    self.expr = expr.into_expression()
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/expression.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    return f"{indent_atom * indent_width}{self.expr.into_code()}"

fn ¤

arg module-attribute ¤

arg = FnArg

Alias FnArg.

FnArg ¤

Bases: IntoCode

Function argument.

Examples:

a = arg(id_("foo")).ty(id_("int")).default(litint(1))
assert a.into_code() == "foo: int = 1"
References

arg.

Source code in synt/stmt/fn.py
class FnArg(IntoCode):
    r"""Function argument.

    Examples:
        ```python
        a = arg(id_("foo")).ty(id_("int")).default(litint(1))
        assert a.into_code() == "foo: int = 1"
        ```

    References:
        [`arg`](https://docs.python.org/3/library/ast.html#ast.arg).
    """

    name: Identifier
    """Argument name."""
    annotation: Expression | None
    """Argument annotation."""
    default_expr: Expression | None
    """Argument default expression."""
    is_vararg: bool
    """Whether the argument is a variable argument, or `*args`."""
    is_kwarg: bool
    """Whether the argument is a keyword argument, or `**kwargs`."""

    def __init__(
        self,
        name: Identifier,
        annotation: IntoExpression | None = None,
        default: IntoExpression | None = None,
        is_vararg: bool = False,
        is_kwarg: bool = False,
    ):
        """Initialize a new argument.

        Args:
            name: Argument keyword.
            annotation: Argument annotation.
            default: Default value for the argument.
            is_vararg: Whether the argument is a variable argument, or `*args`.
            is_kwarg: Whether the argument is a keyword argument, or `**kwargs`.
        """
        self.name = name
        self.annotation = (
            annotation.into_expression() if annotation is not None else None
        )
        self.default_expr = default.into_expression() if default is not None else None
        self.is_vararg = is_vararg
        self.is_kwarg = is_kwarg

    def vararg(self) -> Self:
        """Set the argument as a variable argument."""
        self.is_vararg = True
        return self

    def kwarg(self) -> Self:
        """Set the argument as a keyword argument."""
        self.is_kwarg = True
        return self

    def annotate(self, annotation: IntoExpression) -> Self:
        """Add annotation for the argument.

        Args:
            annotation: Argument annotation.
        """
        self.annotation = annotation.into_expression()
        return self

    def ty(self, annotation: IntoExpression) -> Self:
        """Alias [`annotate`][synt.stmt.fn.FnArg.annotate]."""
        return self.annotate(annotation)

    def default(self, default: IntoExpression) -> Self:
        """Set the default value of the argument.

        Args:
            default: Default value for the argument.
        """
        self.default_expr = default.into_expression()
        return self

    def into_code(self) -> str:
        if self.is_vararg:
            name = f"*{self.name.into_code()}"
        elif self.is_kwarg:
            name = f"**{self.name.into_code()}"
        else:
            name = self.name.into_code()
        ret = name
        if self.annotation is not None:
            ret += f": {self.annotation.into_code()}"
        if self.default_expr is not None:
            ret += f" = {self.default_expr.into_code()}"
        return ret
name instance-attribute ¤
name: Identifier = name

Argument name.

annotation instance-attribute ¤
1
2
3
annotation: Expression | None = (
    into_expression() if annotation is not None else None
)

Argument annotation.

default_expr instance-attribute ¤
1
2
3
default_expr: Expression | None = (
    into_expression() if default is not None else None
)

Argument default expression.

is_vararg instance-attribute ¤
is_vararg: bool = is_vararg

Whether the argument is a variable argument, or *args.

is_kwarg instance-attribute ¤
is_kwarg: bool = is_kwarg

Whether the argument is a keyword argument, or **kwargs.

__init__ ¤
1
2
3
4
5
6
7
__init__(
    name: Identifier,
    annotation: IntoExpression | None = None,
    default: IntoExpression | None = None,
    is_vararg: bool = False,
    is_kwarg: bool = False,
)

Initialize a new argument.

Parameters:

Name Type Description Default
name Identifier

Argument keyword.

required
annotation IntoExpression | None

Argument annotation.

None
default IntoExpression | None

Default value for the argument.

None
is_vararg bool

Whether the argument is a variable argument, or *args.

False
is_kwarg bool

Whether the argument is a keyword argument, or **kwargs.

False
Source code in synt/stmt/fn.py
def __init__(
    self,
    name: Identifier,
    annotation: IntoExpression | None = None,
    default: IntoExpression | None = None,
    is_vararg: bool = False,
    is_kwarg: bool = False,
):
    """Initialize a new argument.

    Args:
        name: Argument keyword.
        annotation: Argument annotation.
        default: Default value for the argument.
        is_vararg: Whether the argument is a variable argument, or `*args`.
        is_kwarg: Whether the argument is a keyword argument, or `**kwargs`.
    """
    self.name = name
    self.annotation = (
        annotation.into_expression() if annotation is not None else None
    )
    self.default_expr = default.into_expression() if default is not None else None
    self.is_vararg = is_vararg
    self.is_kwarg = is_kwarg
vararg ¤
vararg() -> Self

Set the argument as a variable argument.

Source code in synt/stmt/fn.py
def vararg(self) -> Self:
    """Set the argument as a variable argument."""
    self.is_vararg = True
    return self
kwarg ¤
kwarg() -> Self

Set the argument as a keyword argument.

Source code in synt/stmt/fn.py
def kwarg(self) -> Self:
    """Set the argument as a keyword argument."""
    self.is_kwarg = True
    return self
annotate ¤
annotate(annotation: IntoExpression) -> Self

Add annotation for the argument.

Parameters:

Name Type Description Default
annotation IntoExpression

Argument annotation.

required
Source code in synt/stmt/fn.py
def annotate(self, annotation: IntoExpression) -> Self:
    """Add annotation for the argument.

    Args:
        annotation: Argument annotation.
    """
    self.annotation = annotation.into_expression()
    return self
ty ¤
ty(annotation: IntoExpression) -> Self

Alias annotate.

Source code in synt/stmt/fn.py
def ty(self, annotation: IntoExpression) -> Self:
    """Alias [`annotate`][synt.stmt.fn.FnArg.annotate]."""
    return self.annotate(annotation)
default ¤
default(default: IntoExpression) -> Self

Set the default value of the argument.

Parameters:

Name Type Description Default
default IntoExpression

Default value for the argument.

required
Source code in synt/stmt/fn.py
def default(self, default: IntoExpression) -> Self:
    """Set the default value of the argument.

    Args:
        default: Default value for the argument.
    """
    self.default_expr = default.into_expression()
    return self
into_code ¤
into_code() -> str
Source code in synt/stmt/fn.py
def into_code(self) -> str:
    if self.is_vararg:
        name = f"*{self.name.into_code()}"
    elif self.is_kwarg:
        name = f"**{self.name.into_code()}"
    else:
        name = self.name.into_code()
    ret = name
    if self.annotation is not None:
        ret += f": {self.annotation.into_code()}"
    if self.default_expr is not None:
        ret += f" = {self.default_expr.into_code()}"
    return ret

FunctionDef ¤

Bases: Statement

Function definition.

Examples:

With dsl-like aliases:

func = (
    dec(id_("foo"))
    .async_def(id_("bar"))[id_("T")](
        id_("a"),
        arg(id_("b")).ty(id_("int")),
        kw=NONE
    ).returns(id_("float")).block(
        return_(ELLIPSIS)
    )
)
assert func.into_code() == "@foo\nasync def bar[T](a, b: int, kw = None) -> float:\n    return ..."
# @foo
# async def bar[T](a, b: int, kw = None) -> float:
#     return ...

With raw ast:

func = (
    dec(id_("foo"))
    .async_def(id_("bar"))
    .type_param(id_("T"))
    .arg(
        id_("a"),
        arg(id_("b")).ty(id_("int")),
        kw=NONE
    )
    .returns(id_("float"))
    .block(
        return_(ELLIPSIS)
    )
)
assert func.into_code() == "@foo\nasync def bar[T](a, b: int, kw = None) -> float:\n    return ..."
# @foo
# async def bar[T](a, b: int, kw = None) -> float:
#     return ...

References

FunctionDef
AsyncFunctionDef

Source code in synt/stmt/fn.py
class FunctionDef(Statement):
    r"""Function definition.

    Examples:
        With dsl-like aliases:
        ```python
        func = (
            dec(id_("foo"))
            .async_def(id_("bar"))[id_("T")](
                id_("a"),
                arg(id_("b")).ty(id_("int")),
                kw=NONE
            ).returns(id_("float")).block(
                return_(ELLIPSIS)
            )
        )
        assert func.into_code() == "@foo\nasync def bar[T](a, b: int, kw = None) -> float:\n    return ..."
        # @foo
        # async def bar[T](a, b: int, kw = None) -> float:
        #     return ...
        ```

        With raw ast:
        ```python
        func = (
            dec(id_("foo"))
            .async_def(id_("bar"))
            .type_param(id_("T"))
            .arg(
                id_("a"),
                arg(id_("b")).ty(id_("int")),
                kw=NONE
            )
            .returns(id_("float"))
            .block(
                return_(ELLIPSIS)
            )
        )
        assert func.into_code() == "@foo\nasync def bar[T](a, b: int, kw = None) -> float:\n    return ..."
        # @foo
        # async def bar[T](a, b: int, kw = None) -> float:
        #     return ...
        ```

    References:
        [`FunctionDef`](https://docs.python.org/3/library/ast.html#ast.FunctionDef)<br/>
        [`AsyncFunctionDef`](https://docs.python.org/3/library/ast.html#ast.AsyncFunctionDef)
    """

    is_async: bool
    """Whether this function is asynchronous."""
    decorators: list[Expression]
    """Decorators."""
    name: Identifier
    """Function name."""
    type_params: list[TypeParam]
    """Type parameters."""
    args: list[FnArg]
    """Function arguments."""
    returns: Expression | None
    """Return types of the function."""
    body: Block
    """Function body."""

    def __init__(
        self,
        decorators: list[Expression],
        is_async: bool,
        type_params: list[TypeParam],
        args: list[FnArg],
        returns: Expression | None,
        name: Identifier,
        body: Block,
    ):
        """Initialize a function definition.

        **DO NOT USE THIS IN YOUR CODE!**
        """
        self.is_async = is_async
        self.decorators = decorators
        self.type_params = type_params
        self.args = args
        self.returns = returns
        self.name = name
        self.body = body

    def indented(self, indent_width: int, indent_atom: str) -> str:
        indent = indent_width * indent_atom
        decorators = "".join(f"{indent}@{t.into_code()}\n" for t in self.decorators)
        type_param = (
            ""
            if not self.type_params
            else f"[{', '.join(x.into_code() for x in self.type_params)}]"
        )
        args = ", ".join(a.into_code() for a in self.args)
        returns = f" -> {self.returns.into_code()}" if self.returns else ""
        body = self.body.indented(indent_width + 1, indent_atom)
        async_ = "async " if self.is_async else ""
        return f"{decorators}{indent}{async_}def {self.name.into_code()}{type_param}({args}){returns}:\n{body}"
is_async instance-attribute ¤
is_async: bool = is_async

Whether this function is asynchronous.

decorators instance-attribute ¤
decorators: list[Expression] = decorators

Decorators.

type_params instance-attribute ¤
type_params: list[TypeParam] = type_params

Type parameters.

args instance-attribute ¤
args: list[FnArg] = args

Function arguments.

returns instance-attribute ¤
returns: Expression | None = returns

Return types of the function.

name instance-attribute ¤
name: Identifier = name

Function name.

body instance-attribute ¤
body: Block = body

Function body.

__init__ ¤
1
2
3
4
5
6
7
8
9
__init__(
    decorators: list[Expression],
    is_async: bool,
    type_params: list[TypeParam],
    args: list[FnArg],
    returns: Expression | None,
    name: Identifier,
    body: Block,
)

Initialize a function definition.

DO NOT USE THIS IN YOUR CODE!

Source code in synt/stmt/fn.py
def __init__(
    self,
    decorators: list[Expression],
    is_async: bool,
    type_params: list[TypeParam],
    args: list[FnArg],
    returns: Expression | None,
    name: Identifier,
    body: Block,
):
    """Initialize a function definition.

    **DO NOT USE THIS IN YOUR CODE!**
    """
    self.is_async = is_async
    self.decorators = decorators
    self.type_params = type_params
    self.args = args
    self.returns = returns
    self.name = name
    self.body = body
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/fn.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    indent = indent_width * indent_atom
    decorators = "".join(f"{indent}@{t.into_code()}\n" for t in self.decorators)
    type_param = (
        ""
        if not self.type_params
        else f"[{', '.join(x.into_code() for x in self.type_params)}]"
    )
    args = ", ".join(a.into_code() for a in self.args)
    returns = f" -> {self.returns.into_code()}" if self.returns else ""
    body = self.body.indented(indent_width + 1, indent_atom)
    async_ = "async " if self.is_async else ""
    return f"{decorators}{indent}{async_}def {self.name.into_code()}{type_param}({args}){returns}:\n{body}"

FunctionDefBuilder ¤

Function definition builder.

References

FunctionDef

Source code in synt/stmt/fn.py
class FunctionDefBuilder:
    r"""Function definition builder.

    References:
        [`FunctionDef`][synt.stmt.fn.FunctionDef]
    """

    is_async: bool
    """Whether this function is asynchronous."""
    decorators: list[Expression]
    """Decorators."""
    name: Identifier | None
    """Function name."""
    type_params: list[TypeParam]
    """Type parameters."""
    args: list[FnArg]
    """Function arguments."""
    returns_ty: Expression | None
    """Return types of the function."""

    def __init__(self) -> None:
        """Initialize an empty builder."""
        self.is_async = False
        self.decorators = []
        self.type_params = []
        self.args = []
        self.returns_ty = None
        self.name = None

    def async_(self) -> Self:
        """Set this function as asynchronous."""
        self.is_async = True
        return self

    def decorator(self, decorator: IntoExpression) -> Self:
        """Append a decorator.

        Args:
            decorator: Decorator to append.
        """
        self.decorators.append(decorator.into_expression())
        return self

    def dec(self, decorator: IntoExpression) -> Self:
        """Alias [synt.stmt.fn.FunctionDefBuilder.decorator]."""
        return self.decorator(decorator)

    def def_(self, name: Identifier) -> Self:
        """Initialize a function.

        Args:
            name: Function name.
        """
        self.name = name
        return self

    def async_def(self, name: Identifier) -> Self:
        """Initialize an async function.

        This is equivalent to `self.async_().def_(name)`.

        Args:
            name: Function name.
        """
        return self.async_().def_(name)

    def type_param(self, *args: TypeParam | Identifier) -> Self:
        """Add generic type parameters.

        Args:
            *args: Type parameters to add.
        """
        from synt.tokens.ident import Identifier

        self.type_params = [
            TypeVar(x) if isinstance(x, Identifier) else x for x in args
        ]
        return self

    def ty(self, *args: TypeParam | Identifier) -> Self:
        """Alias [`type_param`][synt.stmt.fn.FunctionDefBuilder.type_param]."""
        return self.type_param(*args)

    def __getitem__(
        self, items: tuple[TypeParam | Identifier, ...] | TypeParam | Identifier
    ) -> Self:
        """Alias [`type_param`][synt.stmt.fn.FunctionDefBuilder.type_param]."""
        if isinstance(items, tuple):
            return self.type_param(*items)
        else:
            return self.type_param(items)

    def arg(self, *args: FnArg | Identifier, **kwargs: IntoExpression) -> Self:
        """Add arguments for the function.

        Args:
            *args: Arguments to add.
            **kwargs: Keyword arguments to add with their default values.
        """
        from synt.tokens.ident import Identifier

        self.args = []
        for a in args:
            if isinstance(a, Identifier):
                self.args.append(FnArg(a))
            else:
                self.args.append(a)
        for k, v in kwargs.items():
            self.args.append(FnArg(Identifier(k), default=v.into_expression()))
        return self

    def __call__(self, *args: FnArg | Identifier, **kwargs: IntoExpression) -> Self:
        """Alias [`arg`][synt.stmt.fn.FunctionDefBuilder.arg]."""
        return self.arg(*args, **kwargs)

    def returns(self, returns: IntoExpression) -> Self:
        """Set the return type of the function.

        Args:
            returns: Return type of the function.
        """
        self.returns_ty = returns.into_expression()
        return self

    def block(self, *statements: Statement) -> FunctionDef:
        """Set the block of the function, and build it.

        Args:
            *statements: Statements to include in the function body.

        Raises:
            ValueError: If the required fields (`[name,]`) are not set.
        """
        err_fields = []
        if self.name is None:
            err_fields.append("name")

        if err_fields:
            raise ValueError(
                f"Missing required fields: {', '.join(f'`{t}`' for t in err_fields)}"
            )

        return FunctionDef(
            decorators=self.decorators,
            is_async=self.is_async,
            type_params=self.type_params,
            args=self.args,
            returns=self.returns_ty,
            name=self.name,  # type:ignore[arg-type]
            body=Block(*statements),
        )
is_async instance-attribute ¤
is_async: bool = False

Whether this function is asynchronous.

decorators instance-attribute ¤
decorators: list[Expression] = []

Decorators.

type_params instance-attribute ¤
type_params: list[TypeParam] = []

Type parameters.

args instance-attribute ¤
args: list[FnArg] = []

Function arguments.

returns_ty instance-attribute ¤
returns_ty: Expression | None = None

Return types of the function.

name instance-attribute ¤
name: Identifier | None = None

Function name.

__init__ ¤
__init__() -> None

Initialize an empty builder.

Source code in synt/stmt/fn.py
def __init__(self) -> None:
    """Initialize an empty builder."""
    self.is_async = False
    self.decorators = []
    self.type_params = []
    self.args = []
    self.returns_ty = None
    self.name = None
async_ ¤
async_() -> Self

Set this function as asynchronous.

Source code in synt/stmt/fn.py
def async_(self) -> Self:
    """Set this function as asynchronous."""
    self.is_async = True
    return self
decorator ¤
decorator(decorator: IntoExpression) -> Self

Append a decorator.

Parameters:

Name Type Description Default
decorator IntoExpression

Decorator to append.

required
Source code in synt/stmt/fn.py
def decorator(self, decorator: IntoExpression) -> Self:
    """Append a decorator.

    Args:
        decorator: Decorator to append.
    """
    self.decorators.append(decorator.into_expression())
    return self
dec ¤
dec(decorator: IntoExpression) -> Self

Alias [synt.stmt.fn.FunctionDefBuilder.decorator].

Source code in synt/stmt/fn.py
def dec(self, decorator: IntoExpression) -> Self:
    """Alias [synt.stmt.fn.FunctionDefBuilder.decorator]."""
    return self.decorator(decorator)
def_ ¤
def_(name: Identifier) -> Self

Initialize a function.

Parameters:

Name Type Description Default
name Identifier

Function name.

required
Source code in synt/stmt/fn.py
def def_(self, name: Identifier) -> Self:
    """Initialize a function.

    Args:
        name: Function name.
    """
    self.name = name
    return self
async_def ¤
async_def(name: Identifier) -> Self

Initialize an async function.

This is equivalent to self.async_().def_(name).

Parameters:

Name Type Description Default
name Identifier

Function name.

required
Source code in synt/stmt/fn.py
def async_def(self, name: Identifier) -> Self:
    """Initialize an async function.

    This is equivalent to `self.async_().def_(name)`.

    Args:
        name: Function name.
    """
    return self.async_().def_(name)
type_param ¤
type_param(*args: TypeParam | Identifier) -> Self

Add generic type parameters.

Parameters:

Name Type Description Default
*args TypeParam | Identifier

Type parameters to add.

()
Source code in synt/stmt/fn.py
def type_param(self, *args: TypeParam | Identifier) -> Self:
    """Add generic type parameters.

    Args:
        *args: Type parameters to add.
    """
    from synt.tokens.ident import Identifier

    self.type_params = [
        TypeVar(x) if isinstance(x, Identifier) else x for x in args
    ]
    return self
ty ¤
ty(*args: TypeParam | Identifier) -> Self

Alias type_param.

Source code in synt/stmt/fn.py
def ty(self, *args: TypeParam | Identifier) -> Self:
    """Alias [`type_param`][synt.stmt.fn.FunctionDefBuilder.type_param]."""
    return self.type_param(*args)
__getitem__ ¤
1
2
3
4
5
6
7
__getitem__(
    items: (
        tuple[TypeParam | Identifier, ...]
        | TypeParam
        | Identifier
    )
) -> Self

Alias type_param.

Source code in synt/stmt/fn.py
def __getitem__(
    self, items: tuple[TypeParam | Identifier, ...] | TypeParam | Identifier
) -> Self:
    """Alias [`type_param`][synt.stmt.fn.FunctionDefBuilder.type_param]."""
    if isinstance(items, tuple):
        return self.type_param(*items)
    else:
        return self.type_param(items)
arg ¤
1
2
3
arg(
    *args: FnArg | Identifier, **kwargs: IntoExpression
) -> Self

Add arguments for the function.

Parameters:

Name Type Description Default
*args FnArg | Identifier

Arguments to add.

()
**kwargs IntoExpression

Keyword arguments to add with their default values.

{}
Source code in synt/stmt/fn.py
def arg(self, *args: FnArg | Identifier, **kwargs: IntoExpression) -> Self:
    """Add arguments for the function.

    Args:
        *args: Arguments to add.
        **kwargs: Keyword arguments to add with their default values.
    """
    from synt.tokens.ident import Identifier

    self.args = []
    for a in args:
        if isinstance(a, Identifier):
            self.args.append(FnArg(a))
        else:
            self.args.append(a)
    for k, v in kwargs.items():
        self.args.append(FnArg(Identifier(k), default=v.into_expression()))
    return self
__call__ ¤
1
2
3
__call__(
    *args: FnArg | Identifier, **kwargs: IntoExpression
) -> Self

Alias arg.

Source code in synt/stmt/fn.py
def __call__(self, *args: FnArg | Identifier, **kwargs: IntoExpression) -> Self:
    """Alias [`arg`][synt.stmt.fn.FunctionDefBuilder.arg]."""
    return self.arg(*args, **kwargs)
returns ¤
returns(returns: IntoExpression) -> Self

Set the return type of the function.

Parameters:

Name Type Description Default
returns IntoExpression

Return type of the function.

required
Source code in synt/stmt/fn.py
def returns(self, returns: IntoExpression) -> Self:
    """Set the return type of the function.

    Args:
        returns: Return type of the function.
    """
    self.returns_ty = returns.into_expression()
    return self
block ¤
block(*statements: Statement) -> FunctionDef

Set the block of the function, and build it.

Parameters:

Name Type Description Default
*statements Statement

Statements to include in the function body.

()

Raises:

Type Description
ValueError

If the required fields ([name,]) are not set.

Source code in synt/stmt/fn.py
def block(self, *statements: Statement) -> FunctionDef:
    """Set the block of the function, and build it.

    Args:
        *statements: Statements to include in the function body.

    Raises:
        ValueError: If the required fields (`[name,]`) are not set.
    """
    err_fields = []
    if self.name is None:
        err_fields.append("name")

    if err_fields:
        raise ValueError(
            f"Missing required fields: {', '.join(f'`{t}`' for t in err_fields)}"
        )

    return FunctionDef(
        decorators=self.decorators,
        is_async=self.is_async,
        type_params=self.type_params,
        args=self.args,
        returns=self.returns_ty,
        name=self.name,  # type:ignore[arg-type]
        body=Block(*statements),
    )

vararg ¤

vararg(i: Identifier) -> FnArg

Initialize a variable argument.

This is equivalent to FnArg(...).vararg().

Examples:

va = vararg(id_("foo")).ty(id_("int"))
assert va.into_code() == "*foo: int"
Source code in synt/stmt/fn.py
def vararg(i: Identifier) -> FnArg:
    r"""Initialize a variable argument.

    This is equivalent to `FnArg(...).vararg()`.

    Examples:
        ```python
        va = vararg(id_("foo")).ty(id_("int"))
        assert va.into_code() == "*foo: int"
        ```
    """
    return FnArg(i).vararg()

kwarg ¤

kwarg(i: Identifier) -> FnArg

Initialize a keyword argument.

This is equivalent to FnArg(...).kwarg().

Examples:

va = kwarg(id_("foo")).ty(id_("tuple").expr()[id_("str"), id_("int")])
assert va.into_code() == "**foo: tuple[str, int]"
Source code in synt/stmt/fn.py
def kwarg(i: Identifier) -> FnArg:
    r"""Initialize a keyword argument.

    This is equivalent to `FnArg(...).kwarg()`.

    Examples:
        ```python
        va = kwarg(id_("foo")).ty(id_("tuple").expr()[id_("str"), id_("int")])
        assert va.into_code() == "**foo: tuple[str, int]"
        ```
    """
    return FnArg(i).kwarg()

def_ ¤

Initialize a function definition.

Parameters:

Name Type Description Default
name Identifier

Function name.

required
Source code in synt/stmt/fn.py
def def_(name: Identifier) -> FunctionDefBuilder:
    r"""Initialize a function definition.

    Args:
        name: Function name.
    """
    return FunctionDefBuilder().def_(name)

async_def ¤

async_def(name: Identifier) -> FunctionDefBuilder

Initialize an async function definition.

Parameters:

Name Type Description Default
name Identifier

Function name.

required
Source code in synt/stmt/fn.py
def async_def(name: Identifier) -> FunctionDefBuilder:
    r"""Initialize an async function definition.

    Args:
        name: Function name.
    """
    return FunctionDefBuilder().async_def(name)

importing ¤

import_ module-attribute ¤

import_ = Import

Alias Import.

from_ module-attribute ¤

Import ¤

Bases: Statement

The import statement.

Examples:

1
2
3
4
5
6
im = import_(id_("path"))
assert im.into_code() == "import path"
im = import_(id_("asyncio").as_(id_("aio")))
assert im.into_code() == "import asyncio as aio"
im = import_(path(id_("io"), id_("path")))
assert im.into_code() == "import io.path"
References

Import.

Source code in synt/stmt/importing.py
class Import(Statement):
    r"""The `import` statement.

    Examples:
        ```python
        im = import_(id_("path"))
        assert im.into_code() == "import path"
        im = import_(id_("asyncio").as_(id_("aio")))
        assert im.into_code() == "import asyncio as aio"
        im = import_(path(id_("io"), id_("path")))
        assert im.into_code() == "import io.path"
        ```

    References:
        [`Import`](https://docs.python.org/3/library/ast.html#ast.Import).
    """

    names: list[ImportType]
    """Identifiers that are imported."""

    def __init__(self, *names: ImportType):
        """Initialize a new `import` statement.

        Args:
            names: Identifiers that are imported.

        Raises:
            ValueError: If no import names are provided.
        """
        if len(names) == 0:
            raise ValueError("At least one import name is required.")

        self.names = list(names)

    def indented(self, indent_width: int, indent_atom: str) -> str:
        names: list[str] = []
        for name in self.names:
            if isinstance(name, str):
                names.append(name)
            else:
                names.append(name.into_code())

        return f"{indent_atom * indent_width}import {', '.join(names)}"
names instance-attribute ¤
names: list[ImportType] = list(names)

Identifiers that are imported.

__init__ ¤
__init__(*names: ImportType)

Initialize a new import statement.

Parameters:

Name Type Description Default
names ImportType

Identifiers that are imported.

()

Raises:

Type Description
ValueError

If no import names are provided.

Source code in synt/stmt/importing.py
def __init__(self, *names: ImportType):
    """Initialize a new `import` statement.

    Args:
        names: Identifiers that are imported.

    Raises:
        ValueError: If no import names are provided.
    """
    if len(names) == 0:
        raise ValueError("At least one import name is required.")

    self.names = list(names)
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/importing.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    names: list[str] = []
    for name in self.names:
        if isinstance(name, str):
            names.append(name)
        else:
            names.append(name.into_code())

    return f"{indent_atom * indent_width}import {', '.join(names)}"

ImportFrom ¤

Bases: Statement

The from ... import statement.

Examples:

1
2
3
4
5
6
7
8
fi = from_(id_("io")).import_(id_("path"))
assert fi.into_code() == "from io import path"
fi = from_(id_("io")).import_(id_("path").as_(id_("p")))
assert fi.into_code() == "from io import path as p"
fi = from_(id_("io")).import_(path(id_("path")), id_("os").as_(id_("p")))
assert fi.into_code() == "from io import path, os as p"
fi = from_(id_("io")).import_("*")
assert fi.into_code() == "from io import *"
References

ImportFrom.

Source code in synt/stmt/importing.py
class ImportFrom(Statement):
    r"""The `from ... import` statement.

    Examples:
        ```python
        fi = from_(id_("io")).import_(id_("path"))
        assert fi.into_code() == "from io import path"
        fi = from_(id_("io")).import_(id_("path").as_(id_("p")))
        assert fi.into_code() == "from io import path as p"
        fi = from_(id_("io")).import_(path(id_("path")), id_("os").as_(id_("p")))
        assert fi.into_code() == "from io import path, os as p"
        fi = from_(id_("io")).import_("*")
        assert fi.into_code() == "from io import *"
        ```

    References:
        [`ImportFrom`](https://docs.python.org/3/library/ast.html#ast.ImportFrom).
    """

    module: ModPath
    """The module to import from."""
    names: list[ImportType]
    """Identifiers that are imported."""

    def __init__(self, module: ModPath, *names: ImportType):
        """Initialize a new `from ... import` statement.

        Args:
            module: The module to import from.
            names: Identifiers that are imported.

        Raises:
            ValueError: If no import names are provided.
        """
        if len(names) == 0:
            raise ValueError("At least one import name is required.")

        self.names = list(names)
        self.module = module

    def indented(self, indent_width: int, indent_atom: str) -> str:
        names: list[str] = []
        for name in self.names:
            if isinstance(name, str):
                names.append(name)
            else:
                names.append(name.into_code())

        return f"{indent_atom * indent_width}from {self.module.into_code()} import {', '.join(names)}"
names instance-attribute ¤
names: list[ImportType] = list(names)

Identifiers that are imported.

module instance-attribute ¤
module: ModPath = module

The module to import from.

__init__ ¤
__init__(module: ModPath, *names: ImportType)

Initialize a new from ... import statement.

Parameters:

Name Type Description Default
module ModPath

The module to import from.

required
names ImportType

Identifiers that are imported.

()

Raises:

Type Description
ValueError

If no import names are provided.

Source code in synt/stmt/importing.py
def __init__(self, module: ModPath, *names: ImportType):
    """Initialize a new `from ... import` statement.

    Args:
        module: The module to import from.
        names: Identifiers that are imported.

    Raises:
        ValueError: If no import names are provided.
    """
    if len(names) == 0:
        raise ValueError("At least one import name is required.")

    self.names = list(names)
    self.module = module
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/importing.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    names: list[str] = []
    for name in self.names:
        if isinstance(name, str):
            names.append(name)
        else:
            names.append(name.into_code())

    return f"{indent_atom * indent_width}from {self.module.into_code()} import {', '.join(names)}"

ImportFromBuilder ¤

The builder for ImportFrom.

Source code in synt/stmt/importing.py
class ImportFromBuilder:
    r"""The builder for [`ImportFrom`][synt.stmt.importing.ImportFrom]."""

    module: ModPath
    """The module to import from."""

    def __init__(self, module: ModPath | Identifier):
        """Initialize a new `from ... import` statement builder.

        Args:
            module: The module to import from.
        """
        from synt.expr.modpath import ModPath
        from synt.tokens.ident import Identifier

        if isinstance(module, Identifier):
            self.module = ModPath(module)
        else:
            self.module = module

    def import_(self, *names: ImportType) -> ImportFrom:
        """Import target objects from the module.

        Args:
            names: Items that are imported.

        Raises:
            ValueError: If no import names are provided.
        """
        return ImportFrom(self.module, *names)
module instance-attribute ¤
module: ModPath

The module to import from.

__init__ ¤
__init__(module: ModPath | Identifier)

Initialize a new from ... import statement builder.

Parameters:

Name Type Description Default
module ModPath | Identifier

The module to import from.

required
Source code in synt/stmt/importing.py
def __init__(self, module: ModPath | Identifier):
    """Initialize a new `from ... import` statement builder.

    Args:
        module: The module to import from.
    """
    from synt.expr.modpath import ModPath
    from synt.tokens.ident import Identifier

    if isinstance(module, Identifier):
        self.module = ModPath(module)
    else:
        self.module = module
import_ ¤
import_(*names: ImportType) -> ImportFrom

Import target objects from the module.

Parameters:

Name Type Description Default
names ImportType

Items that are imported.

()

Raises:

Type Description
ValueError

If no import names are provided.

Source code in synt/stmt/importing.py
def import_(self, *names: ImportType) -> ImportFrom:
    """Import target objects from the module.

    Args:
        names: Items that are imported.

    Raises:
        ValueError: If no import names are provided.
    """
    return ImportFrom(self.module, *names)

keyword ¤

PASS module-attribute ¤

PASS = KeywordStatement('pass')

BREAK module-attribute ¤

BREAK = KeywordStatement('break')

CONTINUE module-attribute ¤

CONTINUE = KeywordStatement('continue')

KeywordStatement ¤

Bases: Statement

A statement that only contains a specific keyword.

Examples:

1
2
3
assert PASS.into_code() == "pass"
assert BREAK.into_code() == "break"
assert CONTINUE.into_code() == "continue"
Source code in synt/stmt/keyword.py
class KeywordStatement(Statement):
    r"""A statement that only contains a specific keyword.

    Examples:
        ```python
        assert PASS.into_code() == "pass"
        assert BREAK.into_code() == "break"
        assert CONTINUE.into_code() == "continue"
        ```
    """

    keyword: str

    def __init__(self, keyword: str):
        """Initialize a new keyword statement.

        Args:
            keyword: The keyword to be used in the statement.
        """
        self.keyword = keyword

    def indented(self, indent_width: int, indent_atom: str) -> str:
        return f"{indent_width * indent_atom}{self.keyword}"
keyword instance-attribute ¤
keyword: str = keyword
__init__ ¤
__init__(keyword: str)

Initialize a new keyword statement.

Parameters:

Name Type Description Default
keyword str

The keyword to be used in the statement.

required
Source code in synt/stmt/keyword.py
def __init__(self, keyword: str):
    """Initialize a new keyword statement.

    Args:
        keyword: The keyword to be used in the statement.
    """
    self.keyword = keyword
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/keyword.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    return f"{indent_width * indent_atom}{self.keyword}"

loop ¤

for_ module-attribute ¤

while_ module-attribute ¤

ForLoop ¤

Bases: Statement

The for loop.

Examples:

for_loop = for_(id_("i")).in_(id_("range").expr().call(litint(5))).block(
               if_(id_("i").expr().gt(litint(2))).block(
                   BREAK
               ).else_(
                   CONTINUE
               )
           ).else_(
               PASS
           )
assert for_loop.into_code() == '''for i in range(5):
    if i > 2:
        break
    else:
        continue
else:
    pass'''
# for i in range(5):
#     if i > 2:
#         break
#     else:
#         continue
# else:
#     pass
References

For.

Source code in synt/stmt/loop.py
class ForLoop(Statement):
    r"""The `for` loop.

    Examples:
        ```python
        for_loop = for_(id_("i")).in_(id_("range").expr().call(litint(5))).block(
                       if_(id_("i").expr().gt(litint(2))).block(
                           BREAK
                       ).else_(
                           CONTINUE
                       )
                   ).else_(
                       PASS
                   )
        assert for_loop.into_code() == '''for i in range(5):
            if i > 2:
                break
            else:
                continue
        else:
            pass'''
        # for i in range(5):
        #     if i > 2:
        #         break
        #     else:
        #         continue
        # else:
        #     pass
        ```

    References:
        [`For`](https://docs.python.org/3/library/ast.html#ast.For).
    """

    target: Expression
    """Target item for the iteration.

    Notes:
        Tuples will be automatically unwrapped.
    """
    iter: Expression
    """The expression to iterate over."""
    body: Block
    """The body of the loop."""
    orelse: Block | None
    """The body of the fallback block, aka `for ... else`."""

    def __init__(self, target: IntoExpression, it: IntoExpression, body: Block):
        """Initialize the loop.

        **DO NOT USE THIS IN YOUR CODE!**

        Args:
            target: Target item for the iteration.
            it: The expression to iterate over.
            body: The body of the loop.
        """
        self.target = target.into_expression()
        self.iter = it.into_expression()
        self.body = body
        self.orelse = None

    def else_(self, *statements: Statement) -> Self:
        """Set the fallback `else` block.

        Args:
            statements: The body of the fallback block.
        """
        self.orelse = Block(*statements)
        return self

    def indented(self, indent_width: int, indent_atom: str) -> str:
        indent = indent_atom * indent_width
        if self.orelse is not None:
            else_text = f"\n{indent}else:\n{self.orelse.indented(indent_width + 1, indent_atom)}"
        else:
            else_text = ""
        if is_tuple(self.target):
            target_text = self.target.into_code_implicit()
        else:
            target_text = self.target.into_code()
        return (
            f"{indent}for {target_text} in {self.iter.into_code()}:\n"
            f"{self.body.indented(indent_width + 1, indent_atom)}"
            f"{else_text}"
        )
target instance-attribute ¤
target: Expression = into_expression()

Target item for the iteration.

Notes

Tuples will be automatically unwrapped.

iter instance-attribute ¤
iter: Expression = into_expression()

The expression to iterate over.

body instance-attribute ¤
body: Block = body

The body of the loop.

orelse instance-attribute ¤
orelse: Block | None = None

The body of the fallback block, aka for ... else.

__init__ ¤
1
2
3
__init__(
    target: IntoExpression, it: IntoExpression, body: Block
)

Initialize the loop.

DO NOT USE THIS IN YOUR CODE!

Parameters:

Name Type Description Default
target IntoExpression

Target item for the iteration.

required
it IntoExpression

The expression to iterate over.

required
body Block

The body of the loop.

required
Source code in synt/stmt/loop.py
def __init__(self, target: IntoExpression, it: IntoExpression, body: Block):
    """Initialize the loop.

    **DO NOT USE THIS IN YOUR CODE!**

    Args:
        target: Target item for the iteration.
        it: The expression to iterate over.
        body: The body of the loop.
    """
    self.target = target.into_expression()
    self.iter = it.into_expression()
    self.body = body
    self.orelse = None
else_ ¤
else_(*statements: Statement) -> Self

Set the fallback else block.

Parameters:

Name Type Description Default
statements Statement

The body of the fallback block.

()
Source code in synt/stmt/loop.py
def else_(self, *statements: Statement) -> Self:
    """Set the fallback `else` block.

    Args:
        statements: The body of the fallback block.
    """
    self.orelse = Block(*statements)
    return self
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/loop.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    indent = indent_atom * indent_width
    if self.orelse is not None:
        else_text = f"\n{indent}else:\n{self.orelse.indented(indent_width + 1, indent_atom)}"
    else:
        else_text = ""
    if is_tuple(self.target):
        target_text = self.target.into_code_implicit()
    else:
        target_text = self.target.into_code()
    return (
        f"{indent}for {target_text} in {self.iter.into_code()}:\n"
        f"{self.body.indented(indent_width + 1, indent_atom)}"
        f"{else_text}"
    )

ForLoopBuilder ¤

Builder for for loop.

References

ForLoop.

Source code in synt/stmt/loop.py
class ForLoopBuilder:
    r"""Builder for `for` loop.

    References:
        [`ForLoop`][synt.stmt.loop.ForLoop].
    """

    target: Expression
    """Target item for the iteration."""
    iter: Expression | None
    """The expression to iterate over."""

    def __init__(self, target: IntoExpression):
        """Initialize a new `for` loop builder.

        Args:
            target: Target item for the iteration.
        """
        self.target = target.into_expression()
        self.iter = None

    def in_(self, it: IntoExpression) -> Self:
        """Set the iterator of the loop.

        Args:
            it: The expression to iterate over.
        """
        self.iter = it.into_expression()
        return self

    def block(self, *statements: Statement) -> ForLoop:
        """Set the block of the loop.

        Args:
            *statements: Statements to include in the loop body.

        Raises:
            ValueError: If the required fields (`[iter,]`) are not set.
        """
        err_fields = []
        if self.iter is None:
            err_fields.append("iter")

        if err_fields:
            raise ValueError(
                f"Missing required field(s): {', '.join(f'`{t}`' for t in err_fields)}"
            )

        return ForLoop(self.target, self.iter, Block(*statements))  # type:ignore[arg-type]
target instance-attribute ¤
target: Expression = into_expression()

Target item for the iteration.

iter instance-attribute ¤
iter: Expression | None = None

The expression to iterate over.

__init__ ¤
__init__(target: IntoExpression)

Initialize a new for loop builder.

Parameters:

Name Type Description Default
target IntoExpression

Target item for the iteration.

required
Source code in synt/stmt/loop.py
def __init__(self, target: IntoExpression):
    """Initialize a new `for` loop builder.

    Args:
        target: Target item for the iteration.
    """
    self.target = target.into_expression()
    self.iter = None
in_ ¤
in_(it: IntoExpression) -> Self

Set the iterator of the loop.

Parameters:

Name Type Description Default
it IntoExpression

The expression to iterate over.

required
Source code in synt/stmt/loop.py
def in_(self, it: IntoExpression) -> Self:
    """Set the iterator of the loop.

    Args:
        it: The expression to iterate over.
    """
    self.iter = it.into_expression()
    return self
block ¤
block(*statements: Statement) -> ForLoop

Set the block of the loop.

Parameters:

Name Type Description Default
*statements Statement

Statements to include in the loop body.

()

Raises:

Type Description
ValueError

If the required fields ([iter,]) are not set.

Source code in synt/stmt/loop.py
def block(self, *statements: Statement) -> ForLoop:
    """Set the block of the loop.

    Args:
        *statements: Statements to include in the loop body.

    Raises:
        ValueError: If the required fields (`[iter,]`) are not set.
    """
    err_fields = []
    if self.iter is None:
        err_fields.append("iter")

    if err_fields:
        raise ValueError(
            f"Missing required field(s): {', '.join(f'`{t}`' for t in err_fields)}"
        )

    return ForLoop(self.target, self.iter, Block(*statements))  # type:ignore[arg-type]

WhileLoop ¤

The while loop.

References

While.

Source code in synt/stmt/loop.py
class WhileLoop:
    r"""The `while` loop.

    References:
        [`While`](https://docs.python.org/3/library/ast.html#ast.While).
    """

    test: Expression
    """The condition."""
    orelse: Block | None
    """The body of the fallback block, aka `while ... else`."""

    def __init__(self, test: IntoExpression, body: Block):
        """Initialize a new `while` loop.

        **DO NOT USE THIS IN YOUR CODE!**

        Args:
            test: The condition.
            body: The body of the loop.
        """
        self.test = test.into_expression()
        self.orelse = None
        self.body = body

    def else_(self, *statements: Statement) -> Self:
        """Set the fallback `else` block.

        Args:
            statements: The body of the fallback block.
        """
        self.orelse = Block(*statements)
        return self

    def indented(self, indent_width: int, indent_atom: str) -> str:
        indent = indent_atom * indent_width
        if self.orelse is not None:
            else_text = f"\n{indent}else:\n{self.orelse.indented(indent_width + 1, indent_atom)}"
        else:
            else_text = ""
        return (
            f"{indent}while {self.test.into_code()}:\n"
            f"{self.body.indented(indent_width + 1, indent_atom)}"
            f"{else_text}"
        )
test instance-attribute ¤
test: Expression = into_expression()

The condition.

orelse instance-attribute ¤
orelse: Block | None = None

The body of the fallback block, aka while ... else.

body instance-attribute ¤
body = body
__init__ ¤
__init__(test: IntoExpression, body: Block)

Initialize a new while loop.

DO NOT USE THIS IN YOUR CODE!

Parameters:

Name Type Description Default
test IntoExpression

The condition.

required
body Block

The body of the loop.

required
Source code in synt/stmt/loop.py
def __init__(self, test: IntoExpression, body: Block):
    """Initialize a new `while` loop.

    **DO NOT USE THIS IN YOUR CODE!**

    Args:
        test: The condition.
        body: The body of the loop.
    """
    self.test = test.into_expression()
    self.orelse = None
    self.body = body
else_ ¤
else_(*statements: Statement) -> Self

Set the fallback else block.

Parameters:

Name Type Description Default
statements Statement

The body of the fallback block.

()
Source code in synt/stmt/loop.py
def else_(self, *statements: Statement) -> Self:
    """Set the fallback `else` block.

    Args:
        statements: The body of the fallback block.
    """
    self.orelse = Block(*statements)
    return self
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/loop.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    indent = indent_atom * indent_width
    if self.orelse is not None:
        else_text = f"\n{indent}else:\n{self.orelse.indented(indent_width + 1, indent_atom)}"
    else:
        else_text = ""
    return (
        f"{indent}while {self.test.into_code()}:\n"
        f"{self.body.indented(indent_width + 1, indent_atom)}"
        f"{else_text}"
    )

WhileLoopBuilder ¤

Builder for while loop.

Examples:

while_loop = while_(id_("i").expr().lt(litint(5))).block(
                 id_("i").assign(id_("i").expr() + litint(1))
             ).else_(
                 PASS
             )
assert while_loop.into_code() == '''while i < 5:
    i = i + 1
else:
    pass'''
# while i < 5:
#     i = i + 1
# else:
#     pass
References

WhileLoop.

Source code in synt/stmt/loop.py
class WhileLoopBuilder:
    r"""Builder for `while` loop.

    Examples:
        ```python
        while_loop = while_(id_("i").expr().lt(litint(5))).block(
                         id_("i").assign(id_("i").expr() + litint(1))
                     ).else_(
                         PASS
                     )
        assert while_loop.into_code() == '''while i < 5:
            i = i + 1
        else:
            pass'''
        # while i < 5:
        #     i = i + 1
        # else:
        #     pass
        ```

    References:
        [`WhileLoop`][synt.stmt.loop.WhileLoop].
    """

    test: Expression
    """The condition."""

    def __init__(self, test: IntoExpression):
        """Initialize a new `while` loop builder.

        Args:
            test: The condition.
        """
        self.test = test.into_expression()

    def block(self, *statements: Statement) -> WhileLoop:
        """Set the block of the loop.

        Args:
            *statements: Statements to include in the loop body.
        """
        return WhileLoop(self.test, Block(*statements))
test instance-attribute ¤
test: Expression = into_expression()

The condition.

__init__ ¤
__init__(test: IntoExpression)

Initialize a new while loop builder.

Parameters:

Name Type Description Default
test IntoExpression

The condition.

required
Source code in synt/stmt/loop.py
def __init__(self, test: IntoExpression):
    """Initialize a new `while` loop builder.

    Args:
        test: The condition.
    """
    self.test = test.into_expression()
block ¤
block(*statements: Statement) -> WhileLoop

Set the block of the loop.

Parameters:

Name Type Description Default
*statements Statement

Statements to include in the loop body.

()
Source code in synt/stmt/loop.py
def block(self, *statements: Statement) -> WhileLoop:
    """Set the block of the loop.

    Args:
        *statements: Statements to include in the loop body.
    """
    return WhileLoop(self.test, Block(*statements))

match_case ¤

match_ module-attribute ¤

match_ = Match

Alias Match.

MatchCase ¤

Bases: Statement

A case statement.

References

matchcase.

Source code in synt/stmt/match_case.py
class MatchCase(Statement):
    r"""A `case` statement.

    References:
        [`matchcase`](https://docs.python.org/3/library/ast.html#ast.match_case).
    """

    pattern: Expression
    """Match pattern."""
    guard: Expression | None
    """Pattern guard."""
    body: Block
    """Case body."""

    def __init__(
        self, pattern: IntoExpression, guard: IntoExpression | None, body: Block
    ):
        """Initialize a `case` statement.

        **DO NOT USE THIS IN YOUR CODE!**

        Args:
            pattern: Match pattern.
            guard: Pattern guard.
            body: Case body.
        """
        self.pattern = pattern.into_expression()
        self.guard = guard.into_expression() if guard is not None else None
        self.body = body

    def indented(self, indent_width: int, indent_atom: str) -> str:
        guard = f" if {self.guard.into_code()}" if self.guard is not None else ""
        return (
            f"{indent_atom * indent_width}case {self.pattern.into_code()}{guard}:\n"
            f"{self.body.indented(indent_width + 1, indent_atom)}"
        )
pattern instance-attribute ¤
pattern: Expression = into_expression()

Match pattern.

guard instance-attribute ¤
1
2
3
guard: Expression | None = (
    into_expression() if guard is not None else None
)

Pattern guard.

body instance-attribute ¤
body: Block = body

Case body.

__init__ ¤
1
2
3
4
5
__init__(
    pattern: IntoExpression,
    guard: IntoExpression | None,
    body: Block,
)

Initialize a case statement.

DO NOT USE THIS IN YOUR CODE!

Parameters:

Name Type Description Default
pattern IntoExpression

Match pattern.

required
guard IntoExpression | None

Pattern guard.

required
body Block

Case body.

required
Source code in synt/stmt/match_case.py
def __init__(
    self, pattern: IntoExpression, guard: IntoExpression | None, body: Block
):
    """Initialize a `case` statement.

    **DO NOT USE THIS IN YOUR CODE!**

    Args:
        pattern: Match pattern.
        guard: Pattern guard.
        body: Case body.
    """
    self.pattern = pattern.into_expression()
    self.guard = guard.into_expression() if guard is not None else None
    self.body = body
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/match_case.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    guard = f" if {self.guard.into_code()}" if self.guard is not None else ""
    return (
        f"{indent_atom * indent_width}case {self.pattern.into_code()}{guard}:\n"
        f"{self.body.indented(indent_width + 1, indent_atom)}"
    )

MatchCaseBuilder ¤

Builder for MatchCase.

Source code in synt/stmt/match_case.py
class MatchCaseBuilder:
    """Builder for [`MatchCase`][synt.stmt.match_case.MatchCase]."""

    pattern: Expression
    """Match pattern."""
    guard: Expression | None
    """Pattern guard."""
    parent: Match
    """Parent node."""

    def __init__(self, pattern: IntoExpression, parent: Match):
        """Initialize a new builder.

        Args:
            pattern: Match pattern.
        """
        self.pattern = pattern.into_expression()
        self.guard = None
        self.parent = parent

    def if_(self, guard: IntoExpression) -> Self:
        """Set the guard.

        Args:
            guard: Pattern guard.
        """
        self.guard = guard.into_expression()
        return self

    def block(self, *statements: Statement) -> Match:
        """Set the body statements.

        Args:
            *statements: Body statements.
        """
        case = MatchCase(self.pattern, self.guard, Block(*statements))
        self.parent.cases.append(case)
        return self.parent
pattern instance-attribute ¤
pattern: Expression = into_expression()

Match pattern.

guard instance-attribute ¤
guard: Expression | None = None

Pattern guard.

parent instance-attribute ¤
parent: Match = parent

Parent node.

__init__ ¤
__init__(pattern: IntoExpression, parent: Match)

Initialize a new builder.

Parameters:

Name Type Description Default
pattern IntoExpression

Match pattern.

required
Source code in synt/stmt/match_case.py
def __init__(self, pattern: IntoExpression, parent: Match):
    """Initialize a new builder.

    Args:
        pattern: Match pattern.
    """
    self.pattern = pattern.into_expression()
    self.guard = None
    self.parent = parent
if_ ¤
if_(guard: IntoExpression) -> Self

Set the guard.

Parameters:

Name Type Description Default
guard IntoExpression

Pattern guard.

required
Source code in synt/stmt/match_case.py
def if_(self, guard: IntoExpression) -> Self:
    """Set the guard.

    Args:
        guard: Pattern guard.
    """
    self.guard = guard.into_expression()
    return self
block ¤
block(*statements: Statement) -> Match

Set the body statements.

Parameters:

Name Type Description Default
*statements Statement

Body statements.

()
Source code in synt/stmt/match_case.py
def block(self, *statements: Statement) -> Match:
    """Set the body statements.

    Args:
        *statements: Body statements.
    """
    case = MatchCase(self.pattern, self.guard, Block(*statements))
    self.parent.cases.append(case)
    return self.parent

Match ¤

Bases: Statement

The match statement.

Examples:

match_stmt = (
    match_(id_("a"))
    .case_(id_("b")).block(PASS)
    .case_(id_("Point").expr().call(id_("x"), id_("y"))).block(PASS)
    .case_(list_(id_("x")).as_(id_("y"))).block(PASS)
    .case_(UNDERSCORE).block(PASS)
)
assert match_stmt.into_code() == '''match a:
    case b:
        pass
    case Point(x, y):
        pass
    case [x] as y:
        pass
    case _:
        pass'''
# match a:
#     case b:
#         pass
#     case Point(x, y):
#         pass
#     case [x] as y:
#         pass
#     case _:
#         pass
Notes

Python views [x], (x), etc, as different case nodes, but Synt views them as the same. Synt accepts any form of expression as case patterns, and you must check yourself.

References

Match.

Source code in synt/stmt/match_case.py
class Match(Statement):
    r"""The `match` statement.

    Examples:
        ```python
        match_stmt = (
            match_(id_("a"))
            .case_(id_("b")).block(PASS)
            .case_(id_("Point").expr().call(id_("x"), id_("y"))).block(PASS)
            .case_(list_(id_("x")).as_(id_("y"))).block(PASS)
            .case_(UNDERSCORE).block(PASS)
        )
        assert match_stmt.into_code() == '''match a:
            case b:
                pass
            case Point(x, y):
                pass
            case [x] as y:
                pass
            case _:
                pass'''
        # match a:
        #     case b:
        #         pass
        #     case Point(x, y):
        #         pass
        #     case [x] as y:
        #         pass
        #     case _:
        #         pass
        ```

    Notes:
        Python views `[x]`, `(x)`, etc, as different `case` nodes,
        but Synt views them as the same.
        Synt accepts any form of expression as case patterns,
        and you must check yourself.

    References:
        [`Match`](https://docs.python.org/3/library/ast.html#ast.Match).
    """

    subject: Expression
    """Match subject."""
    cases: list[MatchCase]
    """Match cases."""

    def __init__(self, subject: IntoExpression):
        """Initialize a new `match` statement.

        Args:
            subject: Match subject.
        """
        self.subject = subject.into_expression()
        self.cases = []

    def case_(self, pattern: IntoExpression) -> MatchCaseBuilder:
        """Append a new case.

        Args:
            pattern: Match pattern.
        """
        return MatchCaseBuilder(pattern, self)

    def indented(self, indent_width: int, indent_atom: str) -> str:
        if len(self.cases) == 0:
            cases = f"{indent_atom * (indent_width + 1)}pass"
        else:
            cases = "\n".join(
                x.indented(indent_width + 1, indent_atom) for x in self.cases
            )
        return (
            f"{indent_atom * indent_width}match {self.subject.into_code()}:\n"
            f"{cases}"
        )
subject instance-attribute ¤
subject: Expression = into_expression()

Match subject.

cases instance-attribute ¤
cases: list[MatchCase] = []

Match cases.

__init__ ¤
__init__(subject: IntoExpression)

Initialize a new match statement.

Parameters:

Name Type Description Default
subject IntoExpression

Match subject.

required
Source code in synt/stmt/match_case.py
def __init__(self, subject: IntoExpression):
    """Initialize a new `match` statement.

    Args:
        subject: Match subject.
    """
    self.subject = subject.into_expression()
    self.cases = []
case_ ¤
case_(pattern: IntoExpression) -> MatchCaseBuilder

Append a new case.

Parameters:

Name Type Description Default
pattern IntoExpression

Match pattern.

required
Source code in synt/stmt/match_case.py
def case_(self, pattern: IntoExpression) -> MatchCaseBuilder:
    """Append a new case.

    Args:
        pattern: Match pattern.
    """
    return MatchCaseBuilder(pattern, self)
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/match_case.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    if len(self.cases) == 0:
        cases = f"{indent_atom * (indent_width + 1)}pass"
    else:
        cases = "\n".join(
            x.indented(indent_width + 1, indent_atom) for x in self.cases
        )
    return (
        f"{indent_atom * indent_width}match {self.subject.into_code()}:\n"
        f"{cases}"
    )

namespace ¤

global_ module-attribute ¤

global_ = Global

Alias Global.

nonlocal_ module-attribute ¤

nonlocal_ = Nonlocal

Alias Nonlocal.

Global ¤

Bases: Statement

The global statement.

Examples:

global_stmt = global_(id_('foo'))
assert global_stmt.into_code() == 'global foo'
References

Global.

Source code in synt/stmt/namespace.py
class Global(Statement):
    """The `global` statement.

    Examples:
        ```python
        global_stmt = global_(id_('foo'))
        assert global_stmt.into_code() == 'global foo'
        ```

    References:
        [`Global`](https://docs.python.org/3/library/ast.html#ast.Global).
    """

    names: list[Identifier]
    """Global variable names."""

    def __init__(self, *names: Identifier):
        """Initialize a new `global` statement.

        Args:
            names: Global variable names.

        Raises:
            ValueError: If the `names` list is empty.
        """
        if len(names) == 0:
            raise ValueError("At least one global variable name is required.")
        self.names = list(names)

    def indented(self, indent_width: int, indent_atom: str) -> str:
        return f"{indent_atom * indent_width}global {', '.join(name.into_code() for name in self.names)}"
names instance-attribute ¤

Global variable names.

__init__ ¤
__init__(*names: Identifier)

Initialize a new global statement.

Parameters:

Name Type Description Default
names Identifier

Global variable names.

()

Raises:

Type Description
ValueError

If the names list is empty.

Source code in synt/stmt/namespace.py
def __init__(self, *names: Identifier):
    """Initialize a new `global` statement.

    Args:
        names: Global variable names.

    Raises:
        ValueError: If the `names` list is empty.
    """
    if len(names) == 0:
        raise ValueError("At least one global variable name is required.")
    self.names = list(names)
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/namespace.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    return f"{indent_atom * indent_width}global {', '.join(name.into_code() for name in self.names)}"

Nonlocal ¤

Bases: Statement

The nonlocal statement.

Examples:

nonlocal_stmt = nonlocal_(id_('foo'))
assert nonlocal_stmt.into_code() == 'nonlocal foo'
References

Nonlocal.

Source code in synt/stmt/namespace.py
class Nonlocal(Statement):
    """The `nonlocal` statement.

    Examples:
        ```python
        nonlocal_stmt = nonlocal_(id_('foo'))
        assert nonlocal_stmt.into_code() == 'nonlocal foo'
        ```

    References:
        [`Nonlocal`](https://docs.python.org/3/library/ast.html#ast.Nonlocal).
    """

    names: list[Identifier]
    """Nonlocal variable names."""

    def __init__(self, *names: Identifier):
        """Initialize a new `nonlocal` statement.

        Args:
            names: Nonlocal variable names.

        Raises:
            ValueError: If the `names` list is empty.
        """
        if len(names) == 0:
            raise ValueError("At least one nonlocal variable name is required.")
        self.names = list(names)

    def indented(self, indent_width: int, indent_atom: str) -> str:
        return f"{indent_atom * indent_width}nonlocal {', '.join(name.into_code() for name in self.names)}"
names instance-attribute ¤

Nonlocal variable names.

__init__ ¤
__init__(*names: Identifier)

Initialize a new nonlocal statement.

Parameters:

Name Type Description Default
names Identifier

Nonlocal variable names.

()

Raises:

Type Description
ValueError

If the names list is empty.

Source code in synt/stmt/namespace.py
def __init__(self, *names: Identifier):
    """Initialize a new `nonlocal` statement.

    Args:
        names: Nonlocal variable names.

    Raises:
        ValueError: If the `names` list is empty.
    """
    if len(names) == 0:
        raise ValueError("At least one nonlocal variable name is required.")
    self.names = list(names)
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/namespace.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    return f"{indent_atom * indent_width}nonlocal {', '.join(name.into_code() for name in self.names)}"

raising ¤

raise_ module-attribute ¤

raise_ = Raise

Alias Raise.

Raise ¤

Bases: Statement

The raise statement.

Examples:

1
2
3
4
5
6
r = raise_()
assert r.into_code() == "raise"
r = raise_(litint(42))
assert r.into_code() == "raise 42"
r = raise_(litint(42)).from_(litstr("Custom exception"))
assert r.into_code() == "raise 42 from 'Custom exception'"
References

Raise.

Source code in synt/stmt/raising.py
class Raise(Statement):
    r"""The `raise` statement.

    Examples:
        ```python
        r = raise_()
        assert r.into_code() == "raise"
        r = raise_(litint(42))
        assert r.into_code() == "raise 42"
        r = raise_(litint(42)).from_(litstr("Custom exception"))
        assert r.into_code() == "raise 42 from 'Custom exception'"
        ```

    References:
        [`Raise`](https://docs.python.org/3/library/ast.html#ast.Raise).
    """

    exception: Expression | None
    """The exception to raise."""
    cause: Expression | None
    """The origin of the raised exception."""

    def __init__(self, exception: IntoExpression | None = None):
        """Initialize a new `raise` statement.

        Args:
            exception: The exception to raise.
        """
        if exception:
            self.exception = exception.into_expression()
        else:
            self.exception = None
        self.cause = None

    def from_(self, cause: IntoExpression) -> Self:
        """Set the cause of the raised exception.

        Args:
            cause: The origin of the raised exception.

        Raises:
            ValueError: If `exception` is `None`.
        """
        if self.exception is None:
            raise ValueError("Cannot set cause without setting exception.")
        self.cause = cause.into_expression()
        return self

    def indented(self, indent_width: int, indent_atom: str) -> str:
        cause = f" from {self.cause.into_code()}" if self.cause is not None else ""
        exc = f" {self.exception.into_code()}" if self.exception is not None else ""
        return f"{indent_width * indent_atom}raise{exc}{cause}"
exception instance-attribute ¤
exception: Expression | None

The exception to raise.

cause instance-attribute ¤
cause: Expression | None = None

The origin of the raised exception.

__init__ ¤
__init__(exception: IntoExpression | None = None)

Initialize a new raise statement.

Parameters:

Name Type Description Default
exception IntoExpression | None

The exception to raise.

None
Source code in synt/stmt/raising.py
def __init__(self, exception: IntoExpression | None = None):
    """Initialize a new `raise` statement.

    Args:
        exception: The exception to raise.
    """
    if exception:
        self.exception = exception.into_expression()
    else:
        self.exception = None
    self.cause = None
from_ ¤
from_(cause: IntoExpression) -> Self

Set the cause of the raised exception.

Parameters:

Name Type Description Default
cause IntoExpression

The origin of the raised exception.

required

Raises:

Type Description
ValueError

If exception is None.

Source code in synt/stmt/raising.py
def from_(self, cause: IntoExpression) -> Self:
    """Set the cause of the raised exception.

    Args:
        cause: The origin of the raised exception.

    Raises:
        ValueError: If `exception` is `None`.
    """
    if self.exception is None:
        raise ValueError("Cannot set cause without setting exception.")
    self.cause = cause.into_expression()
    return self
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/raising.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    cause = f" from {self.cause.into_code()}" if self.cause is not None else ""
    exc = f" {self.exception.into_code()}" if self.exception is not None else ""
    return f"{indent_width * indent_atom}raise{exc}{cause}"

returns ¤

return_ module-attribute ¤

return_ = Return

Alias Return.

ret module-attribute ¤

ret = Return

Alias Return.

Return ¤

Bases: Statement

The return statement.

Examples:

1
2
3
4
return_stmt = return_(litint(42))
assert return_stmt.into_code() == "return 42"
return_stmt = ret()
assert return_stmt.into_code() == "return"
References

Returns.

Source code in synt/stmt/returns.py
class Return(Statement):
    r"""The `return` statement.

    Examples:
        ```python
        return_stmt = return_(litint(42))
        assert return_stmt.into_code() == "return 42"
        return_stmt = ret()
        assert return_stmt.into_code() == "return"
        ```

    References:
        [`Returns`](https://docs.python.org/3/library/ast.html#ast.Return).
    """

    expression: Expression | None
    """The value to return from the function."""

    def __init__(self, expression: IntoExpression | None = None):
        """Initialize the return statement.

        Args:
            expression: The value to return from the function.
        """
        if expression:
            self.expression = expression.into_expression()
        else:
            self.expression = None

    def indented(self, indent_width: int, indent_atom: str) -> str:
        if self.expression:
            return f"{indent_atom * indent_width}return {self.expression.into_code()}"
        else:
            return f"{indent_atom * indent_width}return"
expression instance-attribute ¤
expression: Expression | None

The value to return from the function.

__init__ ¤
__init__(expression: IntoExpression | None = None)

Initialize the return statement.

Parameters:

Name Type Description Default
expression IntoExpression | None

The value to return from the function.

None
Source code in synt/stmt/returns.py
def __init__(self, expression: IntoExpression | None = None):
    """Initialize the return statement.

    Args:
        expression: The value to return from the function.
    """
    if expression:
        self.expression = expression.into_expression()
    else:
        self.expression = None
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/returns.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    if self.expression:
        return f"{indent_atom * indent_width}return {self.expression.into_code()}"
    else:
        return f"{indent_atom * indent_width}return"

stmt ¤

IntoStatement ¤

Any type that can be converted into a statement.

Source code in synt/stmt/stmt.py
class IntoStatement(metaclass=ABCMeta):
    r"""Any type that can be converted into a statement."""

    @abstractmethod
    def into_statement(self) -> Statement:
        """Convert the object into a statement."""
into_statement abstractmethod ¤
into_statement() -> Statement

Convert the object into a statement.

Source code in synt/stmt/stmt.py
@abstractmethod
def into_statement(self) -> Statement:
    """Convert the object into a statement."""

Statement ¤

Bases: IntoCode, IntoStatement

A base class for any Python statement.

Source code in synt/stmt/stmt.py
class Statement(IntoCode, IntoStatement, metaclass=ABCMeta):
    r"""A base class for any Python statement."""

    def into_statement(self) -> Statement:
        """A statement can always be converted into a statement."""
        return self

    @abstractmethod
    def indented(self, indent_width: int, indent_atom: str) -> str:
        """Return the code block with appropriate indentation.

        Args:
            indent_width: number of `indent_atom`s per indentation level.
            indent_atom: string to use for indentation. E.g. `\\t`, whitespace, etc.

        Returns:
            indented code block.
        """

    def into_code(self) -> str:
        """Convert the object into a code string."""
        return self.indented(0, "    ")
into_statement ¤
into_statement() -> Statement

A statement can always be converted into a statement.

Source code in synt/stmt/stmt.py
def into_statement(self) -> Statement:
    """A statement can always be converted into a statement."""
    return self
indented abstractmethod ¤
indented(indent_width: int, indent_atom: str) -> str

Return the code block with appropriate indentation.

Parameters:

Name Type Description Default
indent_width int

number of indent_atoms per indentation level.

required
indent_atom str

string to use for indentation. E.g. \t, whitespace, etc.

required

Returns:

Type Description
str

indented code block.

Source code in synt/stmt/stmt.py
@abstractmethod
def indented(self, indent_width: int, indent_atom: str) -> str:
    """Return the code block with appropriate indentation.

    Args:
        indent_width: number of `indent_atom`s per indentation level.
        indent_atom: string to use for indentation. E.g. `\\t`, whitespace, etc.

    Returns:
        indented code block.
    """
into_code ¤
into_code() -> str

Convert the object into a code string.

Source code in synt/stmt/stmt.py
def into_code(self) -> str:
    """Convert the object into a code string."""
    return self.indented(0, "    ")

try_catch ¤

ExceptionHandler ¤

Bases: Statement

Exception handler.

References

ExceptionHandler.

Source code in synt/stmt/try_catch.py
class ExceptionHandler(Statement):
    r"""Exception handler.

    References:
        [`ExceptionHandler`](https://docs.python.org/3/library/ast.html#ast.ExceptHandler).
    """

    is_group: bool
    """Whether the exception handler is a group handler."""
    type: Expression | None
    """The type of exception to catch."""
    asname: Identifier | None
    """The alias name."""
    body: Block
    """The handler body."""

    def __init__(
        self,
        ty: IntoExpression | None,
        is_group: bool,
        asname: Identifier | None,
        body: Block,
    ):
        """Initialize a new exception handler.

        **DO NOT USE THIS IN YOUR CODE!**

        Args:
            ty: The type of exception to catch.
            is_group: Whether the exception handler is a group handler, aka `except*`.
            asname: The alias name.
            body: The handler body.
        """
        if ty is not None:
            self.type = ty.into_expression()
        else:
            self.type = None
        self.is_group = is_group
        self.asname = asname
        self.body = body

    def indented(self, indent_width: int, indent_atom: str) -> str:
        indent = indent_width * indent_atom
        except_kwd = "except*" if self.is_group else "except"
        type_text = f" {self.type.into_code()}" if self.type is not None else ""
        as_text = f" as {self.asname.into_code()}" if self.asname is not None else ""
        return (
            f"{indent}{except_kwd}{type_text}{as_text}:\n"
            f"{self.body.indented(indent_width + 1, indent_atom)}"
        )
type instance-attribute ¤
type: Expression | None

The type of exception to catch.

is_group instance-attribute ¤
is_group: bool = is_group

Whether the exception handler is a group handler.

asname instance-attribute ¤
asname: Identifier | None = asname

The alias name.

body instance-attribute ¤
body: Block = body

The handler body.

__init__ ¤
1
2
3
4
5
6
__init__(
    ty: IntoExpression | None,
    is_group: bool,
    asname: Identifier | None,
    body: Block,
)

Initialize a new exception handler.

DO NOT USE THIS IN YOUR CODE!

Parameters:

Name Type Description Default
ty IntoExpression | None

The type of exception to catch.

required
is_group bool

Whether the exception handler is a group handler, aka except*.

required
asname Identifier | None

The alias name.

required
body Block

The handler body.

required
Source code in synt/stmt/try_catch.py
def __init__(
    self,
    ty: IntoExpression | None,
    is_group: bool,
    asname: Identifier | None,
    body: Block,
):
    """Initialize a new exception handler.

    **DO NOT USE THIS IN YOUR CODE!**

    Args:
        ty: The type of exception to catch.
        is_group: Whether the exception handler is a group handler, aka `except*`.
        asname: The alias name.
        body: The handler body.
    """
    if ty is not None:
        self.type = ty.into_expression()
    else:
        self.type = None
    self.is_group = is_group
    self.asname = asname
    self.body = body
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/try_catch.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    indent = indent_width * indent_atom
    except_kwd = "except*" if self.is_group else "except"
    type_text = f" {self.type.into_code()}" if self.type is not None else ""
    as_text = f" as {self.asname.into_code()}" if self.asname is not None else ""
    return (
        f"{indent}{except_kwd}{type_text}{as_text}:\n"
        f"{self.body.indented(indent_width + 1, indent_atom)}"
    )

ExceptionHandlerBuilder ¤

The builder for exception handlers.

References

ExceptionHandler.

Source code in synt/stmt/try_catch.py
class ExceptionHandlerBuilder:
    r"""The builder for exception handlers.

    References:
        [`ExceptionHandler`][synt.stmt.try_catch.ExceptionHandler].
    """

    is_group: bool
    """Whether the exception handler is a group handler, aka `except*`."""
    type: Expression | None
    """The type of exception to catch."""
    asname: Identifier | None
    """The alias name."""
    parent: Try
    """Parent node."""

    def __init__(self, ty: IntoExpression | None, is_group: bool, parent: Try):
        """Initialize a new exception handler builder.

        Args:
            ty: The type of exception to catch.
            is_group: Whether the exception handler is a group handler, aka `except*`.
            parent: Parent node.
        """
        if ty is not None:
            self.type = ty.into_expression()
        else:
            self.type = None
        self.asname = None
        self.is_group = is_group
        self.parent = parent

    def as_(self, asname: Identifier) -> Self:
        """Set the alias.

        Args:
            asname: The alias name.
        """
        self.asname = asname
        return self

    def block(self, *statements: Statement) -> Try:
        """Set the block of the statement.

        Args:
            statements: The block of the statement.
        """
        handler = ExceptionHandler(
            self.type, self.is_group, self.asname, Block(*statements)
        )
        self.parent.handlers.append(handler)
        return self.parent
type instance-attribute ¤
type: Expression | None

The type of exception to catch.

asname instance-attribute ¤
asname: Identifier | None = None

The alias name.

is_group instance-attribute ¤
is_group: bool = is_group

Whether the exception handler is a group handler, aka except*.

parent instance-attribute ¤
parent: Try = parent

Parent node.

__init__ ¤
1
2
3
__init__(
    ty: IntoExpression | None, is_group: bool, parent: Try
)

Initialize a new exception handler builder.

Parameters:

Name Type Description Default
ty IntoExpression | None

The type of exception to catch.

required
is_group bool

Whether the exception handler is a group handler, aka except*.

required
parent Try

Parent node.

required
Source code in synt/stmt/try_catch.py
def __init__(self, ty: IntoExpression | None, is_group: bool, parent: Try):
    """Initialize a new exception handler builder.

    Args:
        ty: The type of exception to catch.
        is_group: Whether the exception handler is a group handler, aka `except*`.
        parent: Parent node.
    """
    if ty is not None:
        self.type = ty.into_expression()
    else:
        self.type = None
    self.asname = None
    self.is_group = is_group
    self.parent = parent
as_ ¤
as_(asname: Identifier) -> Self

Set the alias.

Parameters:

Name Type Description Default
asname Identifier

The alias name.

required
Source code in synt/stmt/try_catch.py
def as_(self, asname: Identifier) -> Self:
    """Set the alias.

    Args:
        asname: The alias name.
    """
    self.asname = asname
    return self
block ¤
block(*statements: Statement) -> Try

Set the block of the statement.

Parameters:

Name Type Description Default
statements Statement

The block of the statement.

()
Source code in synt/stmt/try_catch.py
def block(self, *statements: Statement) -> Try:
    """Set the block of the statement.

    Args:
        statements: The block of the statement.
    """
    handler = ExceptionHandler(
        self.type, self.is_group, self.asname, Block(*statements)
    )
    self.parent.handlers.append(handler)
    return self.parent

Try ¤

Bases: Statement

The try statement.

Notes

Python views except and except* as separate statement types, but Synt does view them as the same kind and a pair of different variations.

That means if you write except and except* statements together in a single Try, Synt won't complain about it, but the Python parser will reject it.

Examples:

try_block = try_(
                PASS
            ).except_(id_("ValueError")).block(
                PASS
            ).except_(id_("Exception")).as_(id_("e")).block(
                return_()
            ).except_().block(
                raise_()
            ).else_(
                PASS
            ).finally_(
                PASS
            )
assert try_block.into_code() == '''try:
    pass
except ValueError:
    pass
except Exception as e:
    return
except:
    raise
else:
    pass
finally:
    pass'''
# try:
#     pass
# except ValueError:
#     pass
# except Exception as e:
#     return
# except:
#     raise
# finally:
#     pass

try_block = try_(
                PASS
            ).except_star(id_("Exception")).block(
                PASS
            )
assert try_block.into_code() == "try:\n    pass\nexcept* Exception:\n    pass"
# try:
#     pass
# except* Exception:
#     pass
References

Try
TryStar

Source code in synt/stmt/try_catch.py
class Try(Statement):
    r"""The `try` statement.

    Notes:
        Python views `except` and `except*` as separate statement types,
        but Synt does view them as the same kind and a pair of different variations.

        That means if you write `except` and `except*` statements together in a single `Try`,
        Synt won't complain about it, but the Python parser will reject it.

    Examples:
        ```python
        try_block = try_(
                        PASS
                    ).except_(id_("ValueError")).block(
                        PASS
                    ).except_(id_("Exception")).as_(id_("e")).block(
                        return_()
                    ).except_().block(
                        raise_()
                    ).else_(
                        PASS
                    ).finally_(
                        PASS
                    )
        assert try_block.into_code() == '''try:
            pass
        except ValueError:
            pass
        except Exception as e:
            return
        except:
            raise
        else:
            pass
        finally:
            pass'''
        # try:
        #     pass
        # except ValueError:
        #     pass
        # except Exception as e:
        #     return
        # except:
        #     raise
        # finally:
        #     pass

        try_block = try_(
                        PASS
                    ).except_star(id_("Exception")).block(
                        PASS
                    )
        assert try_block.into_code() == "try:\n    pass\nexcept* Exception:\n    pass"
        # try:
        #     pass
        # except* Exception:
        #     pass
        ```

    References:
        [`Try`](https://docs.python.org/3/library/ast.html#ast.Try)<br/>
        [`TryStar`](https://docs.python.org/3/library/ast.html#ast.TryStar)
    """

    try_block: Block
    """The block to catch exceptions."""
    handlers: list[ExceptionHandler]
    """Exception handlers"""
    orelse: Block | None
    """Fallback handler, aka `else`."""
    final: Block | None
    """Final workaround body, aka `finally`."""

    def __init__(
        self,
        try_block: Block,
        handlers: list[ExceptionHandler],
        orelse: Block | None,
        final: Block | None,
    ):
        """Initialize a new `try` statement.

        **DO NOT USE THIS IN YOUR CODE!**

        Args:
            try_block: The block to catch exceptions.
            handlers: Exception handlers.
            orelse: Fallback handler, aka `else`.
            final: Final workaround body, aka `finally`.
        """
        self.try_block = try_block
        self.handlers = handlers
        self.orelse = orelse
        self.final = final

    def except_(self, ty: IntoExpression | None = None) -> ExceptionHandlerBuilder:
        """Append a new exception handler.

        Args:
            ty: The type of exception to catch.
        """
        return ExceptionHandlerBuilder(ty, False, self)

    def except_star(self, ty: IntoExpression | None) -> ExceptionHandlerBuilder:
        """Append a new group exception handler.

        Args:
            ty: The type of exception to catch.
        """
        return ExceptionHandlerBuilder(ty, True, self)

    def else_(self, *statements: Statement) -> Self:
        """Set the fallback handler.

        Args:
            statements: The statements in the fallback handler.
        """
        self.orelse = Block(*statements)
        return self

    def finally_(self, *statements: Statement) -> Self:
        """Set the final workaround body.

        Args:
            statements: The statements in the final workaround body.
        """
        self.final = Block(*statements)
        return self

    def indented(self, indent_width: int, indent_atom: str) -> str:
        indent = indent_atom * indent_width
        if len(self.handlers) > 0:
            handlers_text = "\n" + "\n".join(
                x.indented(indent_width, indent_atom) for x in self.handlers
            )
        else:
            handlers_text = ""
        if self.orelse is not None:
            orelse_text = f"\n{indent}else:\n{self.orelse.indented(indent_width + 1, indent_atom)}"
        else:
            orelse_text = ""
        if self.final is not None:
            final_text = f"\n{indent}finally:\n{self.final.indented(indent_width + 1, indent_atom)}"
        else:
            final_text = ""
        return (
            f"{indent}try:\n{self.try_block.indented(indent_width + 1, indent_atom)}"
            f"{handlers_text}{orelse_text}{final_text}"
        )
try_block instance-attribute ¤
try_block: Block = try_block

The block to catch exceptions.

handlers instance-attribute ¤

Exception handlers

orelse instance-attribute ¤
orelse: Block | None = orelse

Fallback handler, aka else.

final instance-attribute ¤
final: Block | None = final

Final workaround body, aka finally.

__init__ ¤
1
2
3
4
5
6
__init__(
    try_block: Block,
    handlers: list[ExceptionHandler],
    orelse: Block | None,
    final: Block | None,
)

Initialize a new try statement.

DO NOT USE THIS IN YOUR CODE!

Parameters:

Name Type Description Default
try_block Block

The block to catch exceptions.

required
handlers list[ExceptionHandler]

Exception handlers.

required
orelse Block | None

Fallback handler, aka else.

required
final Block | None

Final workaround body, aka finally.

required
Source code in synt/stmt/try_catch.py
def __init__(
    self,
    try_block: Block,
    handlers: list[ExceptionHandler],
    orelse: Block | None,
    final: Block | None,
):
    """Initialize a new `try` statement.

    **DO NOT USE THIS IN YOUR CODE!**

    Args:
        try_block: The block to catch exceptions.
        handlers: Exception handlers.
        orelse: Fallback handler, aka `else`.
        final: Final workaround body, aka `finally`.
    """
    self.try_block = try_block
    self.handlers = handlers
    self.orelse = orelse
    self.final = final
except_ ¤
1
2
3
except_(
    ty: IntoExpression | None = None,
) -> ExceptionHandlerBuilder

Append a new exception handler.

Parameters:

Name Type Description Default
ty IntoExpression | None

The type of exception to catch.

None
Source code in synt/stmt/try_catch.py
def except_(self, ty: IntoExpression | None = None) -> ExceptionHandlerBuilder:
    """Append a new exception handler.

    Args:
        ty: The type of exception to catch.
    """
    return ExceptionHandlerBuilder(ty, False, self)
except_star ¤
1
2
3
except_star(
    ty: IntoExpression | None,
) -> ExceptionHandlerBuilder

Append a new group exception handler.

Parameters:

Name Type Description Default
ty IntoExpression | None

The type of exception to catch.

required
Source code in synt/stmt/try_catch.py
def except_star(self, ty: IntoExpression | None) -> ExceptionHandlerBuilder:
    """Append a new group exception handler.

    Args:
        ty: The type of exception to catch.
    """
    return ExceptionHandlerBuilder(ty, True, self)
else_ ¤
else_(*statements: Statement) -> Self

Set the fallback handler.

Parameters:

Name Type Description Default
statements Statement

The statements in the fallback handler.

()
Source code in synt/stmt/try_catch.py
def else_(self, *statements: Statement) -> Self:
    """Set the fallback handler.

    Args:
        statements: The statements in the fallback handler.
    """
    self.orelse = Block(*statements)
    return self
finally_ ¤
finally_(*statements: Statement) -> Self

Set the final workaround body.

Parameters:

Name Type Description Default
statements Statement

The statements in the final workaround body.

()
Source code in synt/stmt/try_catch.py
def finally_(self, *statements: Statement) -> Self:
    """Set the final workaround body.

    Args:
        statements: The statements in the final workaround body.
    """
    self.final = Block(*statements)
    return self
indented ¤
indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/try_catch.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    indent = indent_atom * indent_width
    if len(self.handlers) > 0:
        handlers_text = "\n" + "\n".join(
            x.indented(indent_width, indent_atom) for x in self.handlers
        )
    else:
        handlers_text = ""
    if self.orelse is not None:
        orelse_text = f"\n{indent}else:\n{self.orelse.indented(indent_width + 1, indent_atom)}"
    else:
        orelse_text = ""
    if self.final is not None:
        final_text = f"\n{indent}finally:\n{self.final.indented(indent_width + 1, indent_atom)}"
    else:
        final_text = ""
    return (
        f"{indent}try:\n{self.try_block.indented(indent_width + 1, indent_atom)}"
        f"{handlers_text}{orelse_text}{final_text}"
    )

try_ ¤

try_(*statement: Statement) -> Try

Initialize a try statement.

Parameters:

Name Type Description Default
statement Statement

The statements in the try block.

()
Source code in synt/stmt/try_catch.py
def try_(*statement: Statement) -> Try:
    r"""Initialize a `try` statement.

    Args:
        statement: The statements in the `try` block.
    """
    return Try(Block(*statement), [], None, None)

tokens ¤

ident ¤

id_ module-attribute ¤

Alias Identifier.

Notes

id is a built-in function in Python, so it's renamed to id_ with a suffix.

Identifier ¤

Bases: IntoExpression, IntoCode

Represents a valid Python identifier.

For more information, see the Identifier and Keywords section of the Python's standard documentation.

Source code in synt/tokens/ident.py
class Identifier(expr.IntoExpression, code.IntoCode):
    r"""Represents a valid Python identifier.

    For more information, see the [Identifier and Keywords][ident-and-keywords-python-docs]
    section of the Python's standard documentation.

    [ident-and-keywords-python-docs]: https://docs.python.org/3.12/reference/lexical_analysis.html#identifiers
    """

    raw: str
    """Raw identifier text."""

    def __init__(self, raw: str):
        """Initialize a new identifier.

        The raw content will be checked immediately when initializing the object.

        Args:
            raw: Raw identifier text.

        Raises:
            InvalidIdentifierException: If the raw identifier text is not a valid identifier.

        Examples:
            ```python
            id_foo = synt.tokens.ident.Identifier('foo')
            id_foo_alias = id_('foo') # with alias
            try:
                id_fail = id_('foo bar') # invalid identifier lit will fail
            except ValueError:
                pass
            ```
        """
        if not raw.isidentifier():
            raise ValueError(f"Invalid identifier: `{raw!r}`")
        self.raw = raw

    def into_expression(self) -> IdentifierExpr:
        return IdentifierExpr(self)

    def expr(self) -> IdentifierExpr:
        """Initialize a new expression with `self`.

        Alias for [`into_expression`][synt.tokens.ident.Identifier.into_expression].

        Examples:
            ```python
            id_foo = id_('foo')
            id_foo_expr = id_foo.expr()
            assert isinstance(id_foo_expr, synt.expr.expr.Expression)
            ```
        """
        return IdentifierExpr(self)

    def into_code(self) -> str:
        return self.raw

    def as_(self, alias: Identifier) -> synt.expr.alias.Alias:
        """Construct a new alias.

        Args:
            alias: The alias name.
        """
        return synt.expr.alias.Alias(self, alias)

    def __hash__(self) -> int:
        return hash(("Identifier", self.raw))
raw instance-attribute ¤
raw: str = raw

Raw identifier text.

__init__ ¤
__init__(raw: str)

Initialize a new identifier.

The raw content will be checked immediately when initializing the object.

Parameters:

Name Type Description Default
raw str

Raw identifier text.

required

Raises:

Type Description
InvalidIdentifierException

If the raw identifier text is not a valid identifier.

Examples:

1
2
3
4
5
6
id_foo = synt.tokens.ident.Identifier('foo')
id_foo_alias = id_('foo') # with alias
try:
    id_fail = id_('foo bar') # invalid identifier lit will fail
except ValueError:
    pass
Source code in synt/tokens/ident.py
def __init__(self, raw: str):
    """Initialize a new identifier.

    The raw content will be checked immediately when initializing the object.

    Args:
        raw: Raw identifier text.

    Raises:
        InvalidIdentifierException: If the raw identifier text is not a valid identifier.

    Examples:
        ```python
        id_foo = synt.tokens.ident.Identifier('foo')
        id_foo_alias = id_('foo') # with alias
        try:
            id_fail = id_('foo bar') # invalid identifier lit will fail
        except ValueError:
            pass
        ```
    """
    if not raw.isidentifier():
        raise ValueError(f"Invalid identifier: `{raw!r}`")
    self.raw = raw
into_expression ¤
into_expression() -> IdentifierExpr
Source code in synt/tokens/ident.py
def into_expression(self) -> IdentifierExpr:
    return IdentifierExpr(self)
expr ¤
expr() -> IdentifierExpr

Initialize a new expression with self.

Alias for into_expression.

Examples:

1
2
3
id_foo = id_('foo')
id_foo_expr = id_foo.expr()
assert isinstance(id_foo_expr, synt.expr.expr.Expression)
Source code in synt/tokens/ident.py
def expr(self) -> IdentifierExpr:
    """Initialize a new expression with `self`.

    Alias for [`into_expression`][synt.tokens.ident.Identifier.into_expression].

    Examples:
        ```python
        id_foo = id_('foo')
        id_foo_expr = id_foo.expr()
        assert isinstance(id_foo_expr, synt.expr.expr.Expression)
        ```
    """
    return IdentifierExpr(self)
into_code ¤
into_code() -> str
Source code in synt/tokens/ident.py
def into_code(self) -> str:
    return self.raw
as_ ¤
as_(alias: Identifier) -> Alias

Construct a new alias.

Parameters:

Name Type Description Default
alias Identifier

The alias name.

required
Source code in synt/tokens/ident.py
def as_(self, alias: Identifier) -> synt.expr.alias.Alias:
    """Construct a new alias.

    Args:
        alias: The alias name.
    """
    return synt.expr.alias.Alias(self, alias)
__hash__ ¤
__hash__() -> int
Source code in synt/tokens/ident.py
def __hash__(self) -> int:
    return hash(("Identifier", self.raw))

IdentifierExpr ¤

Bases: Expression

An identifier as a Python expression.

See Identifier for more information.

Source code in synt/tokens/ident.py
class IdentifierExpr(expr.Expression):
    r"""An identifier as a Python expression.

    See [`Identifier`][synt.tokens.ident.Identifier] for more information.
    """

    precedence = expr.ExprPrecedence.Atom
    expr_type = expr.ExprType.Identifier

    ident: Identifier
    """Inner identifier."""

    def __init__(self, raw: Identifier):
        """Initialize a new identifier.

        Use [`Identifier`][synt.tokens.ident.Identifier.expr] instead and converts it into an expression.

        Args:
            raw: Identifier to be used as an expression.
        """
        self.ident = raw

    @staticmethod
    def from_str(s: str) -> IdentifierExpr:
        """Parse an identifier from a string.

        The raw content will be checked immediately when initializing the object.

        Args:
            s: Raw identifier text.

        Raises:
            InvalidIdentifierException: If the raw identifier text is not a valid identifier.
        """
        return IdentifierExpr(Identifier(s))

    def into_code(self) -> str:
        return self.ident.raw
precedence class-attribute instance-attribute ¤
precedence = Atom
expr_type class-attribute instance-attribute ¤
expr_type = Identifier
ident instance-attribute ¤
ident: Identifier = raw

Inner identifier.

__init__ ¤
__init__(raw: Identifier)

Initialize a new identifier.

Use Identifier instead and converts it into an expression.

Parameters:

Name Type Description Default
raw Identifier

Identifier to be used as an expression.

required
Source code in synt/tokens/ident.py
def __init__(self, raw: Identifier):
    """Initialize a new identifier.

    Use [`Identifier`][synt.tokens.ident.Identifier.expr] instead and converts it into an expression.

    Args:
        raw: Identifier to be used as an expression.
    """
    self.ident = raw
from_str staticmethod ¤
from_str(s: str) -> IdentifierExpr

Parse an identifier from a string.

The raw content will be checked immediately when initializing the object.

Parameters:

Name Type Description Default
s str

Raw identifier text.

required

Raises:

Type Description
InvalidIdentifierException

If the raw identifier text is not a valid identifier.

Source code in synt/tokens/ident.py
@staticmethod
def from_str(s: str) -> IdentifierExpr:
    """Parse an identifier from a string.

    The raw content will be checked immediately when initializing the object.

    Args:
        s: Raw identifier text.

    Raises:
        InvalidIdentifierException: If the raw identifier text is not a valid identifier.
    """
    return IdentifierExpr(Identifier(s))
into_code ¤
into_code() -> str
Source code in synt/tokens/ident.py
def into_code(self) -> str:
    return self.ident.raw

keywords ¤

hard_keywords module-attribute ¤

hard_keywords = kwlist

All Python's hard keywords, in string format.

Alias for std library's keyword.kwlist.

soft_keywords module-attribute ¤

soft_keywords = softkwlist

All Python's soft keywords, in string format.

Alias for std library's keyword.softkwlist.

is_hard_keyword ¤

is_hard_keyword(i: str) -> bool

Check if a string is a hard keyword.

See hard_keywords for more information.

Parameters:

Name Type Description Default
i str

The string to check.

required
Source code in synt/tokens/keywords.py
def is_hard_keyword(i: str) -> bool:
    r"""Check if a string is a hard keyword.

    See [`hard_keywords`][synt.tokens.keywords.hard_keywords] for more information.

    Args:
        i: The string to check.
    """
    return keyword.iskeyword(i)

is_soft_keyword ¤

is_soft_keyword(i: str) -> bool

Check if a string is a soft keyword.

See soft_keywords for more information.

Parameters:

Name Type Description Default
i str

The string to check.

required
Source code in synt/tokens/keywords.py
def is_soft_keyword(i: str) -> bool:
    r"""Check if a string is a soft keyword.

    See [`soft_keywords`][synt.tokens.keywords.soft_keywords] for more information.

    Args:
        i: The string to check.
    """
    return keyword.issoftkeyword(i)

kv_pair ¤

pair module-attribute ¤

pair = KVPair

Alias for KVPair.

kv module-attribute ¤

kv = KVPair

Alias for KVPair.

KVPair ¤

Bases: Expression

A key-value pair, aka a: b.

This is mainly used in dict initializing ({a: b}).

Source code in synt/tokens/kv_pair.py
class KVPair(Expression):
    r"""A key-value pair, aka `a: b`.

    This is mainly used in dict initializing (`{a: b}`)."""

    key: Expression
    """Key expression."""
    value: Expression
    """Value expression."""
    precedence = ExprPrecedence.Atom
    expr_type = ExprType.KeyValuePair

    def __init__(self, key: IntoExpression, value: IntoExpression):
        """Initialize a key-value pair.

        Args:
            key: Key expression.
            value: Value expression.

        Examples:
            ```python
            kv_pair = kv(id_("a"), id_("b"))
            assert kv_pair.into_code() == "a: b"
            ```
        """
        self.key = key.into_expression()
        self.value = value.into_expression()

    def into_code(self) -> str:
        return f"{self.key.into_code()}: {self.value.into_code()}"
precedence class-attribute instance-attribute ¤
precedence = Atom
expr_type class-attribute instance-attribute ¤
expr_type = KeyValuePair
key instance-attribute ¤
key: Expression = into_expression()

Key expression.

value instance-attribute ¤
value: Expression = into_expression()

Value expression.

__init__ ¤
__init__(key: IntoExpression, value: IntoExpression)

Initialize a key-value pair.

Parameters:

Name Type Description Default
key IntoExpression

Key expression.

required
value IntoExpression

Value expression.

required

Examples:

kv_pair = kv(id_("a"), id_("b"))
assert kv_pair.into_code() == "a: b"
Source code in synt/tokens/kv_pair.py
def __init__(self, key: IntoExpression, value: IntoExpression):
    """Initialize a key-value pair.

    Args:
        key: Key expression.
        value: Value expression.

    Examples:
        ```python
        kv_pair = kv(id_("a"), id_("b"))
        assert kv_pair.into_code() == "a: b"
        ```
    """
    self.key = key.into_expression()
    self.value = value.into_expression()
into_code ¤
into_code() -> str
Source code in synt/tokens/kv_pair.py
def into_code(self) -> str:
    return f"{self.key.into_code()}: {self.value.into_code()}"

lit ¤

litstr module-attribute ¤

litstr = str_

Alias for str_.

litint module-attribute ¤

litint = int_

Alias for int_.

litfloat module-attribute ¤

litfloat = float_

Alias for float_.

litbool module-attribute ¤

litbool = bool_

Alias for bool_.

TRUE module-attribute ¤

TRUE = bool_(True)

Alias for bool_(True).

FALSE module-attribute ¤

FALSE = bool_(False)

Alias for bool_(False).

NONE module-attribute ¤

NONE = Literal('None')

Alias for a literal None.

ELLIPSIS module-attribute ¤

ELLIPSIS = Literal('...')

Alias for a literal ellipsis ....

UNDERSCORE module-attribute ¤

UNDERSCORE = Literal('_')

Alias for a literal underscore _.

ELIDE module-attribute ¤

ELIDE = Literal('_')

Alias for a literal underscore _.

Literal ¤

Bases: Expression

Literal Python expression.

Source code in synt/tokens/lit.py
class Literal(Expression):
    r"""Literal Python expression."""

    lit: str
    """Source code of the literal."""

    precedence = ExprPrecedence.Atom
    expr_type = ExprType.Literal

    def __init__(self, src: str):
        """Initialize a Literal value.

        **DO NOT USE THIS IN YOUR CODE!** Use other entry points instead.

        Args:
            src: Source code of the literal.
        """
        self.lit = src

    @staticmethod
    def bool_(b: bool) -> Literal:
        """Initialize a literal boolean.

        Notes:
            `bool` is a built-in type, so this function is suffixed with a `_`.

        Args:
            b: Original boolean.

        Examples:
            ```python
            a = litbool(True)
            assert a.into_code() == "True"
            ```
        """
        if b:
            return Literal("True")
        else:
            return Literal("False")

    @staticmethod
    def str_(s: str) -> Literal:
        """Initialize a literal string.

        Notes:
            `str` is a built-in type, so this function is suffixed with a `_`.

        Args:
            s: Original string.

        Examples:
            ```python
            a = litstr("abc")
            assert a.into_code() == "'abc'"
            ```
        """
        return Literal._repr(s)

    @staticmethod
    def int_(s: int) -> Literal:
        """Initialize a literal integer.

        Notes:
            `int` is a built-in type, so this function is suffixed with a `_`.

        Args:
            s: Original integer.

        Examples:
            ```python
            a = litint(1)
            assert a.into_code() == "1"
            ```
        """
        return Literal._repr(s)

    @staticmethod
    def float_(s: float) -> Literal:
        """Initialize a literal float.

        Args:
            s: Original float.

        Notes:
            `float` is a built-in type, so this function is suffixed with a `_`.

        Examples:
            ```python
            a = litfloat(0.24)
            assert a.into_code() == "0.24"
            ```
        """
        return Literal._repr(s)

    @staticmethod
    def _repr(mr: Any) -> Literal:
        """Initialize a literal value with the `__repr__` method of the given value.

        Args:
            mr: Value to be represented.

        Raises:
            AttributeError: `__repr__` is not found for the given value.
        """
        return Literal(repr(mr))

    @staticmethod
    def _str(s: Any) -> Literal:
        """Initialize a literal value with the `__str__` method of the given value.

        Args:
            s: Value to be represented.

        Raises:
            AttributeError: `__str__` is not found for the given value.
        """
        return Literal(str(s))

    def into_code(self) -> str:
        return self.lit
precedence class-attribute instance-attribute ¤
precedence = Atom
expr_type class-attribute instance-attribute ¤
expr_type = Literal
lit instance-attribute ¤
lit: str = src

Source code of the literal.

__init__ ¤
__init__(src: str)

Initialize a Literal value.

DO NOT USE THIS IN YOUR CODE! Use other entry points instead.

Parameters:

Name Type Description Default
src str

Source code of the literal.

required
Source code in synt/tokens/lit.py
def __init__(self, src: str):
    """Initialize a Literal value.

    **DO NOT USE THIS IN YOUR CODE!** Use other entry points instead.

    Args:
        src: Source code of the literal.
    """
    self.lit = src
bool_ staticmethod ¤
bool_(b: bool) -> Literal

Initialize a literal boolean.

Notes

bool is a built-in type, so this function is suffixed with a _.

Parameters:

Name Type Description Default
b bool

Original boolean.

required

Examples:

a = litbool(True)
assert a.into_code() == "True"
Source code in synt/tokens/lit.py
@staticmethod
def bool_(b: bool) -> Literal:
    """Initialize a literal boolean.

    Notes:
        `bool` is a built-in type, so this function is suffixed with a `_`.

    Args:
        b: Original boolean.

    Examples:
        ```python
        a = litbool(True)
        assert a.into_code() == "True"
        ```
    """
    if b:
        return Literal("True")
    else:
        return Literal("False")
str_ staticmethod ¤
str_(s: str) -> Literal

Initialize a literal string.

Notes

str is a built-in type, so this function is suffixed with a _.

Parameters:

Name Type Description Default
s str

Original string.

required

Examples:

a = litstr("abc")
assert a.into_code() == "'abc'"
Source code in synt/tokens/lit.py
@staticmethod
def str_(s: str) -> Literal:
    """Initialize a literal string.

    Notes:
        `str` is a built-in type, so this function is suffixed with a `_`.

    Args:
        s: Original string.

    Examples:
        ```python
        a = litstr("abc")
        assert a.into_code() == "'abc'"
        ```
    """
    return Literal._repr(s)
int_ staticmethod ¤
int_(s: int) -> Literal

Initialize a literal integer.

Notes

int is a built-in type, so this function is suffixed with a _.

Parameters:

Name Type Description Default
s int

Original integer.

required

Examples:

a = litint(1)
assert a.into_code() == "1"
Source code in synt/tokens/lit.py
@staticmethod
def int_(s: int) -> Literal:
    """Initialize a literal integer.

    Notes:
        `int` is a built-in type, so this function is suffixed with a `_`.

    Args:
        s: Original integer.

    Examples:
        ```python
        a = litint(1)
        assert a.into_code() == "1"
        ```
    """
    return Literal._repr(s)
float_ staticmethod ¤
float_(s: float) -> Literal

Initialize a literal float.

Parameters:

Name Type Description Default
s float

Original float.

required
Notes

float is a built-in type, so this function is suffixed with a _.

Examples:

a = litfloat(0.24)
assert a.into_code() == "0.24"
Source code in synt/tokens/lit.py
@staticmethod
def float_(s: float) -> Literal:
    """Initialize a literal float.

    Args:
        s: Original float.

    Notes:
        `float` is a built-in type, so this function is suffixed with a `_`.

    Examples:
        ```python
        a = litfloat(0.24)
        assert a.into_code() == "0.24"
        ```
    """
    return Literal._repr(s)
into_code ¤
into_code() -> str
Source code in synt/tokens/lit.py
def into_code(self) -> str:
    return self.lit

ty ¤

type_param ¤

tvar module-attribute ¤

tvar = TypeVar

Alias TypeVar.

ttup module-attribute ¤

Alias TypeVarTuple.

tspec module-attribute ¤

Alias TypeParamSpec.

TypeVar ¤

Bases: IntoCode

TypeVar in type parameters.

Examples:

ty_var = tvar(id_("T"), id_("int"))
assert ty_var.into_code() == "T: int"
References

Type parameters.

Source code in synt/ty/type_param.py
class TypeVar(IntoCode):
    r"""`TypeVar` in type parameters.

    Examples:
        ```python
        ty_var = tvar(id_("T"), id_("int"))
        assert ty_var.into_code() == "T: int"
        ```

    References:
        [Type parameters](https://docs.python.org/3/library/ast.html#ast-type-params).
    """

    name: Identifier
    """The name of the type variable."""
    bound: Expression | None
    """The bound of the type variable."""

    def __init__(self, name: Identifier, bound: IntoExpression | None = None):
        """Initialize a type variable.

        Args:
            name: The name of the type variable.
            bound: The bound of the type variable.
        """
        self.name = name
        if bound is not None:
            self.bound = bound.into_expression()
        else:
            self.bound = None

    def into_code(self) -> str:
        bound = f": {self.bound.into_code()}" if self.bound is not None else ""
        return f"{self.name.into_code()}{bound}"
bound instance-attribute ¤
bound: Expression | None

The bound of the type variable.

name instance-attribute ¤
name: Identifier = name

The name of the type variable.

__init__ ¤
1
2
3
__init__(
    name: Identifier, bound: IntoExpression | None = None
)

Initialize a type variable.

Parameters:

Name Type Description Default
name Identifier

The name of the type variable.

required
bound IntoExpression | None

The bound of the type variable.

None
Source code in synt/ty/type_param.py
def __init__(self, name: Identifier, bound: IntoExpression | None = None):
    """Initialize a type variable.

    Args:
        name: The name of the type variable.
        bound: The bound of the type variable.
    """
    self.name = name
    if bound is not None:
        self.bound = bound.into_expression()
    else:
        self.bound = None
into_code ¤
into_code() -> str
Source code in synt/ty/type_param.py
def into_code(self) -> str:
    bound = f": {self.bound.into_code()}" if self.bound is not None else ""
    return f"{self.name.into_code()}{bound}"

TypeVarTuple ¤

Bases: IntoCode

Type variable tuple.

Examples:

ty_var = ttup(id_("T"))
assert ty_var.into_code() == "*T"
References

Type variable tuple.

Source code in synt/ty/type_param.py
class TypeVarTuple(IntoCode):
    r"""Type variable tuple.

    Examples:
        ```python
        ty_var = ttup(id_("T"))
        assert ty_var.into_code() == "*T"
        ```

    References:
        [Type variable tuple](https://docs.python.org/3/library/ast.html#ast.TypeVarTuple).
    """

    name: Identifier
    """The name of the type variable tuple."""

    def __init__(self, name: Identifier):
        """Initialize a type variable tuple.

        Args:
            name: The name of the type variable tuple.
        """
        self.name = name

    def into_code(self) -> str:
        return f"*{self.name.into_code()}"
name instance-attribute ¤
name: Identifier = name

The name of the type variable tuple.

__init__ ¤
__init__(name: Identifier)

Initialize a type variable tuple.

Parameters:

Name Type Description Default
name Identifier

The name of the type variable tuple.

required
Source code in synt/ty/type_param.py
def __init__(self, name: Identifier):
    """Initialize a type variable tuple.

    Args:
        name: The name of the type variable tuple.
    """
    self.name = name
into_code ¤
into_code() -> str
Source code in synt/ty/type_param.py
def into_code(self) -> str:
    return f"*{self.name.into_code()}"

TypeParamSpec ¤

Bases: IntoCode

Type parameter spec.

Examples:

ty_var = tspec(id_("P"))
assert ty_var.into_code() == "**P"
References

Type param spec.

Source code in synt/ty/type_param.py
class TypeParamSpec(IntoCode):
    r"""Type parameter spec.

    Examples:
        ```python
        ty_var = tspec(id_("P"))
        assert ty_var.into_code() == "**P"
        ```

    References:
        [Type param spec](https://docs.python.org/3/library/ast.html#ast.ParamSpec).
    """

    name: Identifier
    """The name of the type variable tuple."""

    def __init__(self, name: Identifier):
        """Initialize a type parameter spec.

        Args:
            name: The name of the type parameter spec.
        """
        self.name = name

    def into_code(self) -> str:
        return f"**{self.name.into_code()}"
name instance-attribute ¤
name: Identifier = name

The name of the type variable tuple.

__init__ ¤
__init__(name: Identifier)

Initialize a type parameter spec.

Parameters:

Name Type Description Default
name Identifier

The name of the type parameter spec.

required
Source code in synt/ty/type_param.py
def __init__(self, name: Identifier):
    """Initialize a type parameter spec.

    Args:
        name: The name of the type parameter spec.
    """
    self.name = name
into_code ¤
into_code() -> str
Source code in synt/ty/type_param.py
def into_code(self) -> str:
    return f"**{self.name.into_code()}"

type_check ¤

is_tuple ¤

is_tuple(exp: Expression) -> TypeGuard[Tuple]

Check if the given expression is a tuple.

Source code in synt/type_check.py
def is_tuple(exp: Expression) -> TypeGuard[synt.expr.tuple.Tuple]:
    r"""Check if the given expression is a tuple."""
    return exp.expr_type == ExprType.Tuple