The object model, descriptors, exception design, cancellation — a week from now some of it will have blurred. Trying to recall it before you reread it is what brings it back sharper, which is the whole reason for this page.
Bookmark this page. Come back in about a week for the first set and about a month for the second. Those gaps are a sensible starting point, not a magic schedule.
- Try each one from memory first. Rereading first skips the part that does the work.
- Use the hints to check. Each names the lesson it comes from.
- Keep a list of the ones you needed help with. That's your reading list.
A week later
1. Predict. Two descriptors, one with __set__ and one without, and an
instance dict that has an entry for both.
class Data:
def __get__(self, instance, owner=None):
return "descriptor"
def __set__(self, instance, value):
pass
class NonData:
def __get__(self, instance, owner=None):
return "descriptor"
class Post:
a = Data()
b = NonData()
post = Post()
post.__dict__.update(a="instance", b="instance")
print(post.a, post.b)Check your prediction
descriptor instanceA data descriptor — one with __set__ — wins over the instance dict; a
non-data descriptor loses to it. That precedence is why a field must define
__set__, and why a cached property must not. From Descriptors: Attributes
With Behaviour.
2. Fix. Narrowing a query shouldn't change the one it came from: this should
print 1 2.
class Query:
def __init__(self, filters=()):
self.filters = list(filters)
def where(self, column, value):
self.filters.append((column, value))
return self
base = Query().where("status", "published")
recent = base.where("year", 2026)
print(len(base.filters), len(recent.filters))Check your fix
class Query:
def __init__(self, filters=()):
self.filters = list(filters)
def where(self, column, value):
return Query([*self.filters, (column, value)])
base = Query().where("status", "published")
recent = base.where("year", 2026)
print(len(base.filters), len(recent.filters))1 2Returning self after mutating made base and recent the same object.
Return a new query instead, and chaining still reads the same. From
Copying, Shallow and Deep.
3. Write a Plugin base class: each subclass registers itself under the
name it's given, and a name that's already taken is refused when the class is
defined. This should print the two lines shown after it:
# class Plugin: ...
class CSV(Plugin, name="csv"):
pass
class JSON(Plugin, name="json"):
pass
try:
class Other(Plugin, name="csv"):
pass
except ValueError as error:
print("refused:", error)
print(sorted(Plugin.registry))refused: 'csv' is taken
['csv', 'json']Check your answer
class Plugin:
registry = {}
def __init_subclass__(cls, name, **kwargs):
super().__init_subclass__(**kwargs)
if name in Plugin.registry:
raise ValueError(f"{name!r} is taken")
Plugin.registry[name] = cls
class CSV(Plugin, name="csv"):
pass
class JSON(Plugin, name="json"):
pass
try:
class Other(Plugin, name="csv"):
pass
except ValueError as error:
print("refused:", error)
print(sorted(Plugin.registry))refused: 'csv' is taken
['csv', 'json']Class keywords arrive as arguments to __init_subclass__, which runs as each
class statement finishes. From init_subclass and What Happens at class.
4. Predict. A task is cancelled while it waits. What does the list hold?
import asyncio
log = []
async def worker():
try:
await asyncio.sleep(10)
except Exception:
log.append("except Exception")
raise
finally:
log.append("finally")
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0)
task.cancel()
try:
await task
except asyncio.CancelledError:
log.append("CancelledError")
print(log)
asyncio.run(main())Check your prediction
['finally', 'CancelledError']CancelledError is a BaseException, not an Exception, so the
except Exception cleanup never runs when a task is cancelled. finally does.
Cleanup that must happen on cancellation belongs in finally (or an
async with). From Cancellation and Cleanup.
A month later
1. Predict both lines.
def fail():
raise ExceptionGroup("batch", [ValueError("a"), KeyError("b"), ValueError("c")])
try:
fail()
except* ValueError as group:
print("values:", len(group.exceptions))
except* KeyError as group:
print("keys:", len(group.exceptions))Check your prediction
values: 2
keys: 1Unlike except, every matching except* clause runs, each receiving the part
of the group it matches. From Tasks, Groups and Exception Groups.
2. Fix. A failed commit should be translated into a StoreError and leave
no transaction open. This should print
StoreError - FOREIGN KEY constraint failed and then
still in a transaction: False.
import contextlib, sqlite3
class StoreError(Exception):
pass
@contextlib.contextmanager
def transaction(conn):
conn.execute("begin")
try:
yield conn
except sqlite3.Error as error:
conn.execute("rollback")
raise StoreError(str(error)) from error
else:
conn.execute("commit")
conn = sqlite3.connect(":memory:", isolation_level=None)
conn.execute("pragma foreign_keys = on")
conn.execute("create table author (id integer primary key)")
conn.execute("create table post (author_id integer"
" references author(id) deferrable initially deferred)")
try:
with transaction(conn):
conn.execute("insert into post values (99)")
except Exception as error:
print(type(error).__name__, "-", error)
print("still in a transaction:", conn.in_transaction)Check your fix
import contextlib, sqlite3
class StoreError(Exception):
pass
@contextlib.contextmanager
def transaction(conn):
conn.execute("begin")
try:
yield conn
conn.execute("commit")
except sqlite3.Error as error:
conn.execute("rollback")
raise StoreError(str(error)) from error
conn = sqlite3.connect(":memory:", isolation_level=None)
conn.execute("pragma foreign_keys = on")
conn.execute("create table author (id integer primary key)")
conn.execute("create table post (author_id integer"
" references author(id) deferrable initially deferred)")
try:
with transaction(conn):
conn.execute("insert into post values (99)")
except Exception as error:
print(type(error).__name__, "-", error)
print("still in a transaction:", conn.in_transaction)StoreError - FOREIGN KEY constraint failed
still in a transaction: FalseA commit is where the database checks deferred constraints, so it can fail.
In the else it was outside the try, so its error escaped untranslated and
nothing rolled back. Inside the try, a failed commit is handled like any other
failure. From Day 4 Checkpoint: Write the Transaction.
3. Write CountingConnection: it wraps a real connection, passes every
execute through, and counts the select statements. This should print 1:
import sqlite3
# class CountingConnection: ...
conn = CountingConnection(sqlite3.connect(":memory:"))
conn.execute("create table t (x)")
conn.execute("insert into t values (?)", (1,))
conn.execute("select * from t")
print(conn.selects)Check your answer
import sqlite3
class CountingConnection:
def __init__(self, real):
self.real = real
self.selects = 0
def execute(self, sql, parameters=(), /):
if sql.lstrip().lower().startswith("select"):
self.selects += 1
return self.real.execute(sql, parameters)
conn = CountingConnection(sqlite3.connect(":memory:"))
conn.execute("create table t (x)")
conn.execute("insert into t values (?)", (1,))
conn.execute("select * from t")
print(conn.selects)1Because the library depends on a Connection protocol, anything with the
right methods can stand in — including a wrapper that counts. From Measuring
Before Optimising and Protocols: Say What You Use.
4. Explain. No code: in the Cursor protocol, why is lastrowid written
as a read-only @property rather than as lastrowid: int | None?
Check your explanation
A plain attribute in a protocol means "readable and writable". sqlite3.Cursor
only lets you read lastrowid, so with the attribute form the real cursor
wouldn't satisfy the protocol, and the checker would reject the very connection
the library was written for. A property says exactly what the library uses:
it reads the value. From Protocols: Say What You Use.
After that
If these came easily, build something: the briefs at the end of On Your Own are a good start. If some didn't, you now know exactly which lessons to reread.
Ready for the next step?
Choose an independent library brief and write down its consumer-facing rules before implementing it. Include accepted input, rejected input, ownership, failure timing, and cleanup. Check it with both local type checking and runtime tests: neither replaces the other. Demonstrate one mutation each suite catches.
You are ready for a larger project when you can explain a limitation without hiding it, reproduce a failure with a small fixture, and measure the property you intend to improve. Try the settings brief or one of its follow-on projects. A real database backend, deeper interpreter internals, and concurrent database access are separate projects; the tiny ORM does not claim to teach or implement them. Return to a delayed challenge whenever an independent attempt reveals a gap.