Skip to content

synt.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()})"