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.
Code
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: PagedQueryHow 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.