Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 10 · Production idioms (modern Python)typing.Self (3.11+) — fluent builders that subclass correctlypredict146 / 161
+150 XP
Task
📝 **Task:** Predict the 4-line output. A Query class has chainable methods returning Self. A TimedQuery subclass adds `.slow(ms)`. Two builds: one with Query, one with TimedQuery. Each prints the rendered SQL and `type(q).__name__` to confirm Self preserved the subclass identity throughout the chain. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

from typing import Self


class Query:
    def __init__(self) -> None:
        self.table: str = ""
        self.filters: list[str] = []
        self.limit_: int | None = None

    def from_(self, table: str) -> Self:
        self.table = table
        return self

    def where(self, cond: str) -> Self:
        self.filters.append(cond)
        return self

    def limit(self, n: int) -> Self:
        self.limit_ = n
        return self

    def build(self) -> str:
        clauses = [f"SELECT * FROM {self.table}"]
        if self.filters:
            clauses.append("WHERE " + " AND ".join(self.filters))
        if self.limit_:
            clauses.append(f"LIMIT {self.limit_}")
        return " ".join(clauses)


class TimedQuery(Query):
    def slow(self, ms: int) -> Self:
        self.filters.append(f"duration_ms > {ms}")
        return self


q = (
    Query()
    .from_("users")
    .where("active = true")
    .where('created_at > "2026-01-01"')
    .limit(10)
)
print(q.build())
print(type(q).__name__)

t = (
    TimedQuery()
    .from_("requests")
    .slow(500)
    .where('path = "/api"')
    .limit(20)
)
print(t.build())
print(type(t).__name__)

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…