Skip to content

synt.stmt.cls ¤

ClassDef ¤

Bases: Statement

Class definition.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Examples:
    ```python
    cls = (
        dec(id_("foo"))
        .class_(id_("Bar"))[id_("T")](metaclass=id_("ABCMeta"))
        .block(
            dec(id_("abstractmethod"))
            .def_(id_("baz"))(id_("self"), arg(id_("a"), id_("T"))).returns(id_("str"))
            .block(
                return_(fstring("Bar(", fnode(id_("a")), ").baz"))
            )
        )
    )
    assert cls.into_code() == '''@foo

class BarT: @abstractmethod def baz(self, a: T) -> str: return f"Bar({a}).baz"'''

1
2
3
4
5
6
7
8
9
    # @foo
    # class Bar[T](metaclass=ABCMeta):
    #     @abstractmethod
    #     def baz(self, a: T) -> str:
    #         return f"Bar({a}).baz"
    ```

References:
    [`ClassDef`](https://docs.python.org/3/library/ast.html#ast.ClassDef).
Source code in synt/stmt/cls.py
class ClassDef(Statement):
    r"""Class definition.

        Examples:
            ```python
            cls = (
                dec(id_("foo"))
                .class_(id_("Bar"))[id_("T")](metaclass=id_("ABCMeta"))
                .block(
                    dec(id_("abstractmethod"))
                    .def_(id_("baz"))(id_("self"), arg(id_("a"), id_("T"))).returns(id_("str"))
                    .block(
                        return_(fstring("Bar(", fnode(id_("a")), ").baz"))
                    )
                )
            )
            assert cls.into_code() == '''@foo
    class Bar[T](metaclass=ABCMeta):
        @abstractmethod
        def baz(self, a: T) -> str:
            return f"Bar({a}).baz"'''

            # @foo
            # class Bar[T](metaclass=ABCMeta):
            #     @abstractmethod
            #     def baz(self, a: T) -> str:
            #         return f"Bar({a}).baz"
            ```

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

    decorators: list[Expression]
    """Decorators."""
    name: Identifier
    """Class name."""
    type_params: list[TypeParam]
    """Type parameters."""
    cargs: list[Expression]
    """Class arguments.

    E.g., base classes.
    """
    ckwargs: list[tuple[Identifier, Expression]]
    """Class keyword arguments.

    E.g., meta classes.
    """
    body: Block
    """Function body."""

    def __init__(
        self,
        decorators: list[Expression],
        type_params: list[TypeParam],
        name: Identifier,
        cargs: list[Expression],
        ckwargs: list[tuple[Identifier, Expression]],
        body: Block,
    ):
        """Initialize a function definition.

        **DO NOT USE THIS IN YOUR CODE!**
        """
        self.decorators = decorators
        self.type_params = type_params
        self.cargs = cargs
        self.ckwargs = ckwargs
        self.name = name
        self.body = body

    def indented(self, indent_width: int, indent_atom: str) -> str:
        indent = indent_width * indent_atom
        decorators = "".join(f"{indent}@{t.into_code()}\n" for t in self.decorators)
        type_param = (
            ""
            if not self.type_params
            else f"[{', '.join(x.into_code() for x in self.type_params)}]"
        )
        args_l: list[str] = []
        args_l.extend(x.into_code() for x in self.cargs)
        args_l.extend(f"{x[0].into_code()}={x[1].into_code()}" for x in self.ckwargs)
        args = f"({', '.join(args_l)})" if args_l else ""
        body = self.body.indented(indent_width + 1, indent_atom)
        return f"{decorators}{indent}class {self.name.into_code()}{type_param}{args}:\n{body}"

decorators instance-attribute ¤

decorators: list[Expression] = decorators

Decorators.

type_params instance-attribute ¤

type_params: list[TypeParam] = type_params

Type parameters.

cargs instance-attribute ¤

Class arguments.

E.g., base classes.

ckwargs instance-attribute ¤

Class keyword arguments.

E.g., meta classes.

name instance-attribute ¤

name: Identifier = name

Class name.

body instance-attribute ¤

body: Block = body

Function body.

__init__ ¤

1
2
3
4
5
6
7
8
__init__(
    decorators: list[Expression],
    type_params: list[TypeParam],
    name: Identifier,
    cargs: list[Expression],
    ckwargs: list[tuple[Identifier, Expression]],
    body: Block,
)

Initialize a function definition.

DO NOT USE THIS IN YOUR CODE!

Source code in synt/stmt/cls.py
def __init__(
    self,
    decorators: list[Expression],
    type_params: list[TypeParam],
    name: Identifier,
    cargs: list[Expression],
    ckwargs: list[tuple[Identifier, Expression]],
    body: Block,
):
    """Initialize a function definition.

    **DO NOT USE THIS IN YOUR CODE!**
    """
    self.decorators = decorators
    self.type_params = type_params
    self.cargs = cargs
    self.ckwargs = ckwargs
    self.name = name
    self.body = body

indented ¤

indented(indent_width: int, indent_atom: str) -> str
Source code in synt/stmt/cls.py
def indented(self, indent_width: int, indent_atom: str) -> str:
    indent = indent_width * indent_atom
    decorators = "".join(f"{indent}@{t.into_code()}\n" for t in self.decorators)
    type_param = (
        ""
        if not self.type_params
        else f"[{', '.join(x.into_code() for x in self.type_params)}]"
    )
    args_l: list[str] = []
    args_l.extend(x.into_code() for x in self.cargs)
    args_l.extend(f"{x[0].into_code()}={x[1].into_code()}" for x in self.ckwargs)
    args = f"({', '.join(args_l)})" if args_l else ""
    body = self.body.indented(indent_width + 1, indent_atom)
    return f"{decorators}{indent}class {self.name.into_code()}{type_param}{args}:\n{body}"

ClassDefBuilder ¤

Class definition builder.

References

ClassDef.

Source code in synt/stmt/cls.py
class ClassDefBuilder:
    r"""Class definition builder.

    References:
        [`ClassDef`][synt.stmt.cls.ClassDef].
    """

    decorators: list[Expression]
    """Decorators."""
    name: Identifier | None
    """Class name."""
    type_params: list[TypeParam]
    """Type parameters."""
    cargs: list[Expression]
    """Class arguments.

    E.g., base classes.
    """
    ckwargs: list[tuple[Identifier, Expression]]
    """Class keyword arguments.

    E.g., meta classes.
    """

    def __init__(self) -> None:
        """Initialize an empty builder."""
        self.decorators = []
        self.name = None
        self.type_params = []
        self.cargs = []
        self.ckwargs = []

    def decorator(self, decorator: IntoExpression) -> Self:
        """Append a decorator.

        Args:
            decorator: Decorator to append.
        """
        self.decorators.append(decorator.into_expression())
        return self

    def dec(self, decorator: IntoExpression) -> Self:
        """Alias [`decorator`][synt.stmt.cls.ClassDefBuilder.decorator]."""
        return self.decorator(decorator)

    def class_(self, name: Identifier) -> Self:
        """Initialize a class.

        Args:
            name: Class name.
        """
        self.name = name
        return self

    def type_param(self, *args: TypeParam | Identifier) -> Self:
        """Add generic type parameters.

        Args:
            *args: Type parameters to add.
        """
        from synt.tokens.ident import Identifier

        self.type_params = [
            TypeVar(x) if isinstance(x, Identifier) else x for x in args
        ]
        return self

    def ty(self, *args: TypeParam | Identifier) -> Self:
        """Alias [`type_param`][synt.stmt.cls.ClassDefBuilder.type_param]."""
        return self.type_param(*args)

    def __getitem__(
        self, items: tuple[TypeParam | Identifier, ...] | TypeParam | Identifier
    ) -> Self:
        """Alias [`type_param`][synt.stmt.cls.ClassDefBuilder.type_param]."""
        if isinstance(items, tuple):
            return self.type_param(*items)
        else:
            return self.type_param(items)

    def arg(
        self,
        *args: IntoExpression | tuple[Identifier, IntoExpression],
        **kwargs: IntoExpression,
    ) -> Self:
        """Add arguments for the class.

        Args:
            *args: Arguments to add.
            **kwargs: Keyword arguments to add with their default values.
        """
        from synt.tokens.ident import Identifier

        self.cargs = []
        self.ckwargs = []
        for a in args:
            if isinstance(a, tuple):
                self.ckwargs.append((a[0], a[1].into_expression()))
            else:
                self.cargs.append(a.into_expression())
        for k, v in kwargs.items():
            self.ckwargs.append((Identifier(k), v.into_expression()))
        return self

    def __call__(
        self,
        *args: IntoExpression | tuple[Identifier, IntoExpression],
        **kwargs: IntoExpression,
    ) -> Self:
        """Alias [`arg`][synt.stmt.cls.ClassDefBuilder.arg]."""
        return self.arg(*args, **kwargs)

    def block(self, *statements: Statement) -> ClassDef:
        """Set the block of the class, and build it.

        Args:
            *statements: Statements to include in the class body.

        Raises:
            ValueError: If the required fields (`[name,]`) are not set.
        """
        err_fields = []
        if self.name is None:
            err_fields.append("name")

        if err_fields:
            raise ValueError(
                f"Missing required fields: {', '.join(f'`{t}`' for t in err_fields)}"
            )

        return ClassDef(
            decorators=self.decorators,
            type_params=self.type_params,
            cargs=self.cargs,
            ckwargs=self.ckwargs,
            name=self.name,  # type:ignore[arg-type]
            body=Block(*statements),
        )

decorators instance-attribute ¤

decorators: list[Expression] = []

Decorators.

name instance-attribute ¤

name: Identifier | None = None

Class name.

type_params instance-attribute ¤

type_params: list[TypeParam] = []

Type parameters.

cargs instance-attribute ¤

cargs: list[Expression] = []

Class arguments.

E.g., base classes.

ckwargs instance-attribute ¤

ckwargs: list[tuple[Identifier, Expression]] = []

Class keyword arguments.

E.g., meta classes.

__init__ ¤

__init__() -> None

Initialize an empty builder.

Source code in synt/stmt/cls.py
def __init__(self) -> None:
    """Initialize an empty builder."""
    self.decorators = []
    self.name = None
    self.type_params = []
    self.cargs = []
    self.ckwargs = []

decorator ¤

decorator(decorator: IntoExpression) -> Self

Append a decorator.

Parameters:

Name Type Description Default
decorator IntoExpression

Decorator to append.

required
Source code in synt/stmt/cls.py
def decorator(self, decorator: IntoExpression) -> Self:
    """Append a decorator.

    Args:
        decorator: Decorator to append.
    """
    self.decorators.append(decorator.into_expression())
    return self

dec ¤

dec(decorator: IntoExpression) -> Self

Alias decorator.

Source code in synt/stmt/cls.py
def dec(self, decorator: IntoExpression) -> Self:
    """Alias [`decorator`][synt.stmt.cls.ClassDefBuilder.decorator]."""
    return self.decorator(decorator)

class_ ¤

class_(name: Identifier) -> Self

Initialize a class.

Parameters:

Name Type Description Default
name Identifier

Class name.

required
Source code in synt/stmt/cls.py
def class_(self, name: Identifier) -> Self:
    """Initialize a class.

    Args:
        name: Class name.
    """
    self.name = name
    return self

type_param ¤

type_param(*args: TypeParam | Identifier) -> Self

Add generic type parameters.

Parameters:

Name Type Description Default
*args TypeParam | Identifier

Type parameters to add.

()
Source code in synt/stmt/cls.py
def type_param(self, *args: TypeParam | Identifier) -> Self:
    """Add generic type parameters.

    Args:
        *args: Type parameters to add.
    """
    from synt.tokens.ident import Identifier

    self.type_params = [
        TypeVar(x) if isinstance(x, Identifier) else x for x in args
    ]
    return self

ty ¤

ty(*args: TypeParam | Identifier) -> Self

Alias type_param.

Source code in synt/stmt/cls.py
def ty(self, *args: TypeParam | Identifier) -> Self:
    """Alias [`type_param`][synt.stmt.cls.ClassDefBuilder.type_param]."""
    return self.type_param(*args)

__getitem__ ¤

1
2
3
4
5
6
7
__getitem__(
    items: (
        tuple[TypeParam | Identifier, ...]
        | TypeParam
        | Identifier
    )
) -> Self

Alias type_param.

Source code in synt/stmt/cls.py
def __getitem__(
    self, items: tuple[TypeParam | Identifier, ...] | TypeParam | Identifier
) -> Self:
    """Alias [`type_param`][synt.stmt.cls.ClassDefBuilder.type_param]."""
    if isinstance(items, tuple):
        return self.type_param(*items)
    else:
        return self.type_param(items)

arg ¤

Add arguments for the class.

Parameters:

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

Arguments to add.

()
**kwargs IntoExpression

Keyword arguments to add with their default values.

{}
Source code in synt/stmt/cls.py
def arg(
    self,
    *args: IntoExpression | tuple[Identifier, IntoExpression],
    **kwargs: IntoExpression,
) -> Self:
    """Add arguments for the class.

    Args:
        *args: Arguments to add.
        **kwargs: Keyword arguments to add with their default values.
    """
    from synt.tokens.ident import Identifier

    self.cargs = []
    self.ckwargs = []
    for a in args:
        if isinstance(a, tuple):
            self.ckwargs.append((a[0], a[1].into_expression()))
        else:
            self.cargs.append(a.into_expression())
    for k, v in kwargs.items():
        self.ckwargs.append((Identifier(k), v.into_expression()))
    return self

__call__ ¤

1
2
3
4
5
__call__(
    *args: IntoExpression
    | tuple[Identifier, IntoExpression],
    **kwargs: IntoExpression
) -> Self

Alias arg.

Source code in synt/stmt/cls.py
def __call__(
    self,
    *args: IntoExpression | tuple[Identifier, IntoExpression],
    **kwargs: IntoExpression,
) -> Self:
    """Alias [`arg`][synt.stmt.cls.ClassDefBuilder.arg]."""
    return self.arg(*args, **kwargs)

block ¤

block(*statements: Statement) -> ClassDef

Set the block of the class, and build it.

Parameters:

Name Type Description Default
*statements Statement

Statements to include in the class body.

()

Raises:

Type Description
ValueError

If the required fields ([name,]) are not set.

Source code in synt/stmt/cls.py
def block(self, *statements: Statement) -> ClassDef:
    """Set the block of the class, and build it.

    Args:
        *statements: Statements to include in the class body.

    Raises:
        ValueError: If the required fields (`[name,]`) are not set.
    """
    err_fields = []
    if self.name is None:
        err_fields.append("name")

    if err_fields:
        raise ValueError(
            f"Missing required fields: {', '.join(f'`{t}`' for t in err_fields)}"
        )

    return ClassDef(
        decorators=self.decorators,
        type_params=self.type_params,
        cargs=self.cargs,
        ckwargs=self.ckwargs,
        name=self.name,  # type:ignore[arg-type]
        body=Block(*statements),
    )

class_ ¤

class_(name: Identifier) -> ClassDefBuilder

Initialize a class without decorators.

Parameters:

Name Type Description Default
name Identifier

Class name.

required
Source code in synt/stmt/cls.py
def class_(name: Identifier) -> ClassDefBuilder:
    r"""Initialize a class without decorators.

    Args:
        name: Class name.
    """
    return ClassDefBuilder().class_(name)