typing.Self Types Fluent Builder Returns

Annotate fluent methods with typing.Self so subclasses keep their own return type, then chain configuration calls and build the final query.

PythonConfig Management

Code

pythonsnippet
43 lines
from typing import Self


class QueryBuilder:
    def __init__(self) -> None:
        self.parts: list[str] = []

    def select(self, *columns: str) -> Self:
        self.parts.append("SELECT " + ", ".join(columns))
        return self

    def from_table(self, table: str) -> Self:
        self.parts.append("FROM " + table)
        return self

    def where(self, condition: str) -> Self:
        self.parts.append("WHERE " + condition)
        return self

    def build(self) -> str:
        return " ".join(self.parts)


class PagedQuery(QueryBuilder):
    def limit(self, rows: int) -> Self:
        self.parts.append("LIMIT " + str(rows))
        return self


def main() -> None:
    query = (
        PagedQuery()
        .select("id", "email")
        .from_table("users")
        .where("active = true")
        .limit(25)
    )
    print(query.build())
    print("subclass kept:", type(query.select("id")).__name__)


if __name__ == "__main__":
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

SELECT id, email FROM users WHERE active = true LIMIT 25
subclass kept: PagedQuery

How the snippet works

One way to read it: the classes QueryBuilder, PagedQuery and kept and the functions __init__, select, from_table and where, doing all the work.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Applying it

Signature: def select(self, *columns: str) -> Self

Output lines are prefixed (subclass kept:), making each step’s effect easy to spot.

The entry point wires select, from_table, where and limit together — run it once and the whole demo flows.

Statements that matter

def __init__(self) -> None:
    self.parts: list[str] = []
def main() -> None:
    query = (
        PagedQuery()
        .select("id", "email")
        .from_table("users")
        .where("active = true")
        .limit(25)
    )
    print(query.build())
    print("subclass kept:", type(query.select("id")).__name__)
def from_table(self, table: str) -> Self:
    self.parts.append("FROM " + table)
    return self

Interactive Tools for This Topic

FAQ

What does typing.Self Types Fluent Builder Returns print when run?
No setup needed: run the file and look for labeled lines like `subclass kept:` in the output.