Skip to content

synt.tokens ¤

ident ¤

id_ module-attribute ¤

Alias Identifier.

Notes

id is a built-in function in Python, so it's renamed to id_ with a suffix.

Identifier ¤

Bases: IntoExpression, IntoCode

Represents a valid Python identifier.

For more information, see the Identifier and Keywords section of the Python's standard documentation.

Source code in synt/tokens/ident.py
class Identifier(expr.IntoExpression, code.IntoCode):
    r"""Represents a valid Python identifier.

    For more information, see the [Identifier and Keywords][ident-and-keywords-python-docs]
    section of the Python's standard documentation.

    [ident-and-keywords-python-docs]: https://docs.python.org/3.12/reference/lexical_analysis.html#identifiers
    """

    raw: str
    """Raw identifier text."""

    def __init__(self, raw: str):
        """Initialize a new identifier.

        The raw content will be checked immediately when initializing the object.

        Args:
            raw: Raw identifier text.

        Raises:
            InvalidIdentifierException: If the raw identifier text is not a valid identifier.

        Examples:
            ```python
            id_foo = synt.tokens.ident.Identifier('foo')
            id_foo_alias = id_('foo') # with alias
            try:
                id_fail = id_('foo bar') # invalid identifier lit will fail
            except ValueError:
                pass
            ```
        """
        if not raw.isidentifier():
            raise ValueError(f"Invalid identifier: `{raw!r}`")
        self.raw = raw

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

    def expr(self) -> IdentifierExpr:
        """Initialize a new expression with `self`.

        Alias for [`into_expression`][synt.tokens.ident.Identifier.into_expression].

        Examples:
            ```python
            id_foo = id_('foo')
            id_foo_expr = id_foo.expr()
            assert isinstance(id_foo_expr, synt.expr.expr.Expression)
            ```
        """
        return IdentifierExpr(self)

    def into_code(self) -> str:
        return self.raw

    def as_(self, alias: Identifier) -> synt.expr.alias.Alias:
        """Construct a new alias.

        Args:
            alias: The alias name.
        """
        return synt.expr.alias.Alias(self, alias)

    def __hash__(self) -> int:
        return hash(("Identifier", self.raw))

raw instance-attribute ¤

raw: str = raw

Raw identifier text.

__init__ ¤

__init__(raw: str)

Initialize a new identifier.

The raw content will be checked immediately when initializing the object.

Parameters:

Name Type Description Default
raw str

Raw identifier text.

required

Raises:

Type Description
InvalidIdentifierException

If the raw identifier text is not a valid identifier.

Examples:

1
2
3
4
5
6
id_foo = synt.tokens.ident.Identifier('foo')
id_foo_alias = id_('foo') # with alias
try:
    id_fail = id_('foo bar') # invalid identifier lit will fail
except ValueError:
    pass
Source code in synt/tokens/ident.py
def __init__(self, raw: str):
    """Initialize a new identifier.

    The raw content will be checked immediately when initializing the object.

    Args:
        raw: Raw identifier text.

    Raises:
        InvalidIdentifierException: If the raw identifier text is not a valid identifier.

    Examples:
        ```python
        id_foo = synt.tokens.ident.Identifier('foo')
        id_foo_alias = id_('foo') # with alias
        try:
            id_fail = id_('foo bar') # invalid identifier lit will fail
        except ValueError:
            pass
        ```
    """
    if not raw.isidentifier():
        raise ValueError(f"Invalid identifier: `{raw!r}`")
    self.raw = raw

into_expression ¤

into_expression() -> IdentifierExpr
Source code in synt/tokens/ident.py
def into_expression(self) -> IdentifierExpr:
    return IdentifierExpr(self)

expr ¤

expr() -> IdentifierExpr

Initialize a new expression with self.

Alias for into_expression.

Examples:

1
2
3
id_foo = id_('foo')
id_foo_expr = id_foo.expr()
assert isinstance(id_foo_expr, synt.expr.expr.Expression)
Source code in synt/tokens/ident.py
def expr(self) -> IdentifierExpr:
    """Initialize a new expression with `self`.

    Alias for [`into_expression`][synt.tokens.ident.Identifier.into_expression].

    Examples:
        ```python
        id_foo = id_('foo')
        id_foo_expr = id_foo.expr()
        assert isinstance(id_foo_expr, synt.expr.expr.Expression)
        ```
    """
    return IdentifierExpr(self)

into_code ¤

into_code() -> str
Source code in synt/tokens/ident.py
def into_code(self) -> str:
    return self.raw

as_ ¤

as_(alias: Identifier) -> Alias

Construct a new alias.

Parameters:

Name Type Description Default
alias Identifier

The alias name.

required
Source code in synt/tokens/ident.py
def as_(self, alias: Identifier) -> synt.expr.alias.Alias:
    """Construct a new alias.

    Args:
        alias: The alias name.
    """
    return synt.expr.alias.Alias(self, alias)

__hash__ ¤

__hash__() -> int
Source code in synt/tokens/ident.py
def __hash__(self) -> int:
    return hash(("Identifier", self.raw))

IdentifierExpr ¤

Bases: Expression

An identifier as a Python expression.

See Identifier for more information.

Source code in synt/tokens/ident.py
class IdentifierExpr(expr.Expression):
    r"""An identifier as a Python expression.

    See [`Identifier`][synt.tokens.ident.Identifier] for more information.
    """

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

    ident: Identifier
    """Inner identifier."""

    def __init__(self, raw: Identifier):
        """Initialize a new identifier.

        Use [`Identifier`][synt.tokens.ident.Identifier.expr] instead and converts it into an expression.

        Args:
            raw: Identifier to be used as an expression.
        """
        self.ident = raw

    @staticmethod
    def from_str(s: str) -> IdentifierExpr:
        """Parse an identifier from a string.

        The raw content will be checked immediately when initializing the object.

        Args:
            s: Raw identifier text.

        Raises:
            InvalidIdentifierException: If the raw identifier text is not a valid identifier.
        """
        return IdentifierExpr(Identifier(s))

    def into_code(self) -> str:
        return self.ident.raw

precedence class-attribute instance-attribute ¤

precedence = Atom

expr_type class-attribute instance-attribute ¤

expr_type = Identifier

ident instance-attribute ¤

ident: Identifier = raw

Inner identifier.

__init__ ¤

__init__(raw: Identifier)

Initialize a new identifier.

Use Identifier instead and converts it into an expression.

Parameters:

Name Type Description Default
raw Identifier

Identifier to be used as an expression.

required
Source code in synt/tokens/ident.py
def __init__(self, raw: Identifier):
    """Initialize a new identifier.

    Use [`Identifier`][synt.tokens.ident.Identifier.expr] instead and converts it into an expression.

    Args:
        raw: Identifier to be used as an expression.
    """
    self.ident = raw

from_str staticmethod ¤

from_str(s: str) -> IdentifierExpr

Parse an identifier from a string.

The raw content will be checked immediately when initializing the object.

Parameters:

Name Type Description Default
s str

Raw identifier text.

required

Raises:

Type Description
InvalidIdentifierException

If the raw identifier text is not a valid identifier.

Source code in synt/tokens/ident.py
@staticmethod
def from_str(s: str) -> IdentifierExpr:
    """Parse an identifier from a string.

    The raw content will be checked immediately when initializing the object.

    Args:
        s: Raw identifier text.

    Raises:
        InvalidIdentifierException: If the raw identifier text is not a valid identifier.
    """
    return IdentifierExpr(Identifier(s))

into_code ¤

into_code() -> str
Source code in synt/tokens/ident.py
def into_code(self) -> str:
    return self.ident.raw

keywords ¤

hard_keywords module-attribute ¤

hard_keywords = kwlist

All Python's hard keywords, in string format.

Alias for std library's keyword.kwlist.

soft_keywords module-attribute ¤

soft_keywords = softkwlist

All Python's soft keywords, in string format.

Alias for std library's keyword.softkwlist.

is_hard_keyword ¤

is_hard_keyword(i: str) -> bool

Check if a string is a hard keyword.

See hard_keywords for more information.

Parameters:

Name Type Description Default
i str

The string to check.

required
Source code in synt/tokens/keywords.py
def is_hard_keyword(i: str) -> bool:
    r"""Check if a string is a hard keyword.

    See [`hard_keywords`][synt.tokens.keywords.hard_keywords] for more information.

    Args:
        i: The string to check.
    """
    return keyword.iskeyword(i)

is_soft_keyword ¤

is_soft_keyword(i: str) -> bool

Check if a string is a soft keyword.

See soft_keywords for more information.

Parameters:

Name Type Description Default
i str

The string to check.

required
Source code in synt/tokens/keywords.py
def is_soft_keyword(i: str) -> bool:
    r"""Check if a string is a soft keyword.

    See [`soft_keywords`][synt.tokens.keywords.soft_keywords] for more information.

    Args:
        i: The string to check.
    """
    return keyword.issoftkeyword(i)

kv_pair ¤

pair module-attribute ¤

pair = KVPair

Alias for KVPair.

kv module-attribute ¤

kv = KVPair

Alias for KVPair.

KVPair ¤

Bases: Expression

A key-value pair, aka a: b.

This is mainly used in dict initializing ({a: b}).

Source code in synt/tokens/kv_pair.py
class KVPair(Expression):
    r"""A key-value pair, aka `a: b`.

    This is mainly used in dict initializing (`{a: b}`)."""

    key: Expression
    """Key expression."""
    value: Expression
    """Value expression."""
    precedence = ExprPrecedence.Atom
    expr_type = ExprType.KeyValuePair

    def __init__(self, key: IntoExpression, value: IntoExpression):
        """Initialize a key-value pair.

        Args:
            key: Key expression.
            value: Value expression.

        Examples:
            ```python
            kv_pair = kv(id_("a"), id_("b"))
            assert kv_pair.into_code() == "a: b"
            ```
        """
        self.key = key.into_expression()
        self.value = value.into_expression()

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

precedence class-attribute instance-attribute ¤

precedence = Atom

expr_type class-attribute instance-attribute ¤

expr_type = KeyValuePair

key instance-attribute ¤

key: Expression = into_expression()

Key expression.

value instance-attribute ¤

value: Expression = into_expression()

Value expression.

__init__ ¤

__init__(key: IntoExpression, value: IntoExpression)

Initialize a key-value pair.

Parameters:

Name Type Description Default
key IntoExpression

Key expression.

required
value IntoExpression

Value expression.

required

Examples:

kv_pair = kv(id_("a"), id_("b"))
assert kv_pair.into_code() == "a: b"
Source code in synt/tokens/kv_pair.py
def __init__(self, key: IntoExpression, value: IntoExpression):
    """Initialize a key-value pair.

    Args:
        key: Key expression.
        value: Value expression.

    Examples:
        ```python
        kv_pair = kv(id_("a"), id_("b"))
        assert kv_pair.into_code() == "a: b"
        ```
    """
    self.key = key.into_expression()
    self.value = value.into_expression()

into_code ¤

into_code() -> str
Source code in synt/tokens/kv_pair.py
def into_code(self) -> str:
    return f"{self.key.into_code()}: {self.value.into_code()}"

lit ¤

litstr module-attribute ¤

litstr = str_

Alias for str_.

litint module-attribute ¤

litint = int_

Alias for int_.

litfloat module-attribute ¤

litfloat = float_

Alias for float_.

litbool module-attribute ¤

litbool = bool_

Alias for bool_.

TRUE module-attribute ¤

TRUE = bool_(True)

Alias for bool_(True).

FALSE module-attribute ¤

FALSE = bool_(False)

Alias for bool_(False).

NONE module-attribute ¤

NONE = Literal('None')

Alias for a literal None.

ELLIPSIS module-attribute ¤

ELLIPSIS = Literal('...')

Alias for a literal ellipsis ....

UNDERSCORE module-attribute ¤

UNDERSCORE = Literal('_')

Alias for a literal underscore _.

ELIDE module-attribute ¤

ELIDE = Literal('_')

Alias for a literal underscore _.

Literal ¤

Bases: Expression

Literal Python expression.

Source code in synt/tokens/lit.py
class Literal(Expression):
    r"""Literal Python expression."""

    lit: str
    """Source code of the literal."""

    precedence = ExprPrecedence.Atom
    expr_type = ExprType.Literal

    def __init__(self, src: str):
        """Initialize a Literal value.

        **DO NOT USE THIS IN YOUR CODE!** Use other entry points instead.

        Args:
            src: Source code of the literal.
        """
        self.lit = src

    @staticmethod
    def bool_(b: bool) -> Literal:
        """Initialize a literal boolean.

        Notes:
            `bool` is a built-in type, so this function is suffixed with a `_`.

        Args:
            b: Original boolean.

        Examples:
            ```python
            a = litbool(True)
            assert a.into_code() == "True"
            ```
        """
        if b:
            return Literal("True")
        else:
            return Literal("False")

    @staticmethod
    def str_(s: str) -> Literal:
        """Initialize a literal string.

        Notes:
            `str` is a built-in type, so this function is suffixed with a `_`.

        Args:
            s: Original string.

        Examples:
            ```python
            a = litstr("abc")
            assert a.into_code() == "'abc'"
            ```
        """
        return Literal._repr(s)

    @staticmethod
    def int_(s: int) -> Literal:
        """Initialize a literal integer.

        Notes:
            `int` is a built-in type, so this function is suffixed with a `_`.

        Args:
            s: Original integer.

        Examples:
            ```python
            a = litint(1)
            assert a.into_code() == "1"
            ```
        """
        return Literal._repr(s)

    @staticmethod
    def float_(s: float) -> Literal:
        """Initialize a literal float.

        Args:
            s: Original float.

        Notes:
            `float` is a built-in type, so this function is suffixed with a `_`.

        Examples:
            ```python
            a = litfloat(0.24)
            assert a.into_code() == "0.24"
            ```
        """
        return Literal._repr(s)

    @staticmethod
    def _repr(mr: Any) -> Literal:
        """Initialize a literal value with the `__repr__` method of the given value.

        Args:
            mr: Value to be represented.

        Raises:
            AttributeError: `__repr__` is not found for the given value.
        """
        return Literal(repr(mr))

    @staticmethod
    def _str(s: Any) -> Literal:
        """Initialize a literal value with the `__str__` method of the given value.

        Args:
            s: Value to be represented.

        Raises:
            AttributeError: `__str__` is not found for the given value.
        """
        return Literal(str(s))

    def into_code(self) -> str:
        return self.lit

precedence class-attribute instance-attribute ¤

precedence = Atom

expr_type class-attribute instance-attribute ¤

expr_type = Literal

lit instance-attribute ¤

lit: str = src

Source code of the literal.

__init__ ¤

__init__(src: str)

Initialize a Literal value.

DO NOT USE THIS IN YOUR CODE! Use other entry points instead.

Parameters:

Name Type Description Default
src str

Source code of the literal.

required
Source code in synt/tokens/lit.py
def __init__(self, src: str):
    """Initialize a Literal value.

    **DO NOT USE THIS IN YOUR CODE!** Use other entry points instead.

    Args:
        src: Source code of the literal.
    """
    self.lit = src

bool_ staticmethod ¤

bool_(b: bool) -> Literal

Initialize a literal boolean.

Notes

bool is a built-in type, so this function is suffixed with a _.

Parameters:

Name Type Description Default
b bool

Original boolean.

required

Examples:

a = litbool(True)
assert a.into_code() == "True"
Source code in synt/tokens/lit.py
@staticmethod
def bool_(b: bool) -> Literal:
    """Initialize a literal boolean.

    Notes:
        `bool` is a built-in type, so this function is suffixed with a `_`.

    Args:
        b: Original boolean.

    Examples:
        ```python
        a = litbool(True)
        assert a.into_code() == "True"
        ```
    """
    if b:
        return Literal("True")
    else:
        return Literal("False")

str_ staticmethod ¤

str_(s: str) -> Literal

Initialize a literal string.

Notes

str is a built-in type, so this function is suffixed with a _.

Parameters:

Name Type Description Default
s str

Original string.

required

Examples:

a = litstr("abc")
assert a.into_code() == "'abc'"
Source code in synt/tokens/lit.py
@staticmethod
def str_(s: str) -> Literal:
    """Initialize a literal string.

    Notes:
        `str` is a built-in type, so this function is suffixed with a `_`.

    Args:
        s: Original string.

    Examples:
        ```python
        a = litstr("abc")
        assert a.into_code() == "'abc'"
        ```
    """
    return Literal._repr(s)

int_ staticmethod ¤

int_(s: int) -> Literal

Initialize a literal integer.

Notes

int is a built-in type, so this function is suffixed with a _.

Parameters:

Name Type Description Default
s int

Original integer.

required

Examples:

a = litint(1)
assert a.into_code() == "1"
Source code in synt/tokens/lit.py
@staticmethod
def int_(s: int) -> Literal:
    """Initialize a literal integer.

    Notes:
        `int` is a built-in type, so this function is suffixed with a `_`.

    Args:
        s: Original integer.

    Examples:
        ```python
        a = litint(1)
        assert a.into_code() == "1"
        ```
    """
    return Literal._repr(s)

float_ staticmethod ¤

float_(s: float) -> Literal

Initialize a literal float.

Parameters:

Name Type Description Default
s float

Original float.

required
Notes

float is a built-in type, so this function is suffixed with a _.

Examples:

a = litfloat(0.24)
assert a.into_code() == "0.24"
Source code in synt/tokens/lit.py
@staticmethod
def float_(s: float) -> Literal:
    """Initialize a literal float.

    Args:
        s: Original float.

    Notes:
        `float` is a built-in type, so this function is suffixed with a `_`.

    Examples:
        ```python
        a = litfloat(0.24)
        assert a.into_code() == "0.24"
        ```
    """
    return Literal._repr(s)

into_code ¤

into_code() -> str
Source code in synt/tokens/lit.py
def into_code(self) -> str:
    return self.lit