Skip to content
Tech Interview Prep
Technical interview guide

OOP & Data Classes

Classes, inheritance, and the @dataclass shortcut for the common case of a class that's mostly just data.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v3
Editorial status
Reviewed

Scope: Python 3.14 object model, dataclasses, typing.Protocol, and abstract base classes.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Contrast instance and class attributes for mutable state.

Answer

Core answer. A class attribute lives on the class object and is shared by every instance; an instance attribute lives in that instance's __dict__ and is private to it. Assignment through self.name = value writes the instance __dict__ (unless a data descriptor intercepts it), creating a per-instance attribute that shadows the class one. Mutation through self.name.append(...) is not an assignment: it reads the shared class object and mutates it in place. That asymmetry is why items = [] in a class body becomes an accidental global.

Why lookup behaves that way. obj.attr first walks type(obj).__mro__ looking for a data descriptor (a class attribute defining __set__ or __delete__); if one exists it wins outright. Otherwise Python checks obj.__dict__, then falls back to the class attribute: a plain value or a non-data descriptor. Assignment obj.attr = v skips that walk entirely unless a data descriptor defines __set__; it writes obj.__dict__. Read can reach the class, write never does.

Python
class Cart:
    items = []                      # one list object, on the class
    def __init__(self, owner):
        self.owner = owner          # instance attribute

a, b = Cart("a"), Cart("b")
a.items.append("apple")             # read class attr, mutate it
print(b.items, a.items is b.items)  # ['apple'] True
a.items = ["pear"]                  # assignment -> instance __dict__
print(b.items, a.items is b.items)  # ['apple'] False

Trace: a.items.append finds no data descriptor named items on Cart, finds nothing in a.__dict__, and resolves to the class list. The same object b.items resolves to, so the append is visible to b. a.items = ["pear"] finds no data descriptor, so it writes a.__dict__['items']; from then on a.items stops at the instance dict and b still sees the class list.

instance attributeclass attribute
stored inobj.__dict__type(obj).__dict__
visible tothat instance onlyall instances that don't shadow it
created byself.x = vx = v in the class body
mutable default risknoneshared across instances
with __slots__must be a declared slotstill readable, not assignable

Alternatives and when to use them. For per-instance mutable state, initialise in __init__ (self.items = []) or use @dataclass with field(default_factory=list). A dataclass with items: list = [] raises ValueError: mutable default <class 'list'> for field items is not allowed at class-definition time, so that trap is caught for you. Use a class attribute deliberately for shared, read-mostly configuration (a default timeout, a registry, a cache keyed by class) and make it immutable (tuple, frozenset, MappingProxyType) when instances must not mutate it. __slots__ removes __dict__ entirely, so a class attribute of the same name becomes read-only from instances: self.items = [...] raises AttributeError.

Failure modes to name. Shared-list bleed between instances (detected by a.items is b.items returning True); the same bug via a mutable default argument, def __init__(self, items=[]), evaluated once at def time; subclass code that assigns a class attribute and silently changes behaviour for the parent's other instances; and __slots__ classes where the class attribute shadows the intended slot. Test construction, equality, and inheritance explicitly: those are where the sharing shows up.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Walk me through the division of labour between `__new__` and `__init__`, and when overriding `__new__` is the right call.

Answer

type.__call__ orchestrates construction in two steps: obj = cls.__new__(cls, *args, **kwargs), then cls.__init__(obj, *args, **kwargs), but only if isinstance(obj, cls). So __new__ allocates and returns the instance; __init__ configures an instance that already exists and must return None. __new__ is special-cased as a static method because it runs before any instance exists, so there is no self to bind; it takes cls explicitly so subclasses allocate the right type. It must return an instance: returning None silently skips __init__ and makes the call expression evaluate to None.

Trace for Point2D(3, 4):

stepcallnote
1Point2D.__new__(Point2D, 3, 4)allocates, returns instance
2isinstance(obj, Point2D)gate that decides whether __init__ runs
3Point2D.__init__(obj, 3, 4)configures, returns None
4type.__call__ returns obj

Override __new__ in three situations.

1. Immutable built-ins. tuple, int, str and frozenset fix their value at allocation. By the time __init__ runs the object is already immutable, so __init__ cannot set it: the value has to go through super().__new__.

python class Point2D(tuple): def new(cls, x, y): return super().new(cls, (x, y))

2. Returning an existing instance: interning, flyweight, a per-process singleton. __new__ may return anything, and if what it returns is not an instance of cls, __init__ is skipped entirely.

3. Enforcing an allocation policy: rejecting construction, returning a subclass instance, or handing back a cached object.

__init__ cannot cover these because it receives an already-allocated object and can only mutate it. It cannot change identity, cannot return a different object (a non-None return raises TypeError), and cannot run before an immutable value is fixed.

Failure modes worth naming:

  • A singleton built on __new__ still runs __init__ on every construction, because the cached object is an instance of cls. Guard with a flag or move the policy to a metaclass.
  • Forgetting return in __new__ yields None with no exception at the call site: the bug surfaces later as an AttributeError on the result.
  • An immutable subclass whose __new__ requires arguments breaks copy.copy and pickle unless you implement __getnewargs__ (or __reduce__), because the default reconstruction path calls cls.__new__(cls) with no arguments.
  • __new__ returning an instance of a different class skips __init__, so any setup there never runs and you get a silently half-built object.

Alternatives: for ordinary mutable classes, __init__ alone is correct; for alternate constructors use @classmethod; for singletons a module-level instance or a metaclass is usually clearer than __new__.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Design a polymorphic alternate constructor with `classmethod`.

Answer

Core answer (first 90 seconds)

A polymorphic alternate constructor is a classmethod that builds an instance from an input __init__ doesn't take (polar coordinates, a dict, a wire record) and returns cls(...) instead of a hard-coded class name. classmethod is a descriptor: ColoredPoint.from_polar finds the function on Point through the MRO, then __get__(None, ColoredPoint) binds cls=ColoredPoint. So cls(...) constructs the subclass and every subclass inherits the constructor for free.

The invariant you have to design for: whatever positional arguments the classmethod passes must be acceptable to the subclass's __init__. Two ways to hold that invariant: keep subclass signatures compatible (extra fields defaulted), or forward **kwargs from the classmethod so the subclass supplies its own fields.

Python
import math

class Point:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y

    @classmethod
    def from_polar(cls, r, theta, **kwargs):
        return cls(r * math.cos(theta), r * math.sin(theta), **kwargs)

    def __repr__(self):
        return f"{type(self).__name__}(x={self.x:.3f}, y={self.y:.3f})"

class ColoredPoint(Point):
    __slots__ = ("color",)

    def __init__(self, x, y, color="black"):
        super().__init__(x, y)
        self.color = color

class TaggedPoint(Point):
    __slots__ = ("tag",)

    def __init__(self, x, y, tag):
        super().__init__(x, y)
        self.tag = tag

Trace (CPython 3.12):

>>> ColoredPoint.from_polar(1.0, 0.0)
ColoredPoint(x=1.000, y=0.000)
>>> ColoredPoint.from_polar(1.0, 0.0).color
'black'
>>> TaggedPoint.from_polar(1.0, 0.0, tag="origin").tag
'origin'
>>> Point.from_polar(1.0, 0.0)
Point(x=1.000, y=0.000)

Step by step for the first call: lookup finds from_polar on Point, the descriptor binds cls=ColoredPoint; the body computes 1.0*cos(0)=1.0 and 1.0*sin(0)=0.0; cls(1.0, 0.0) calls ColoredPoint.__init__, which defaults color="black"; type(result) is ColoredPoint, not Point.

Failure modes

  • Hard-coding the base class, return Point(r*math.cos(theta), r*math.sin(theta)), returns a Point from ColoredPoint.from_polar. isinstance still passes, so the bug hides until subclass state is missing. Detect with assert type(obj) is cls in the constructor's tests.
  • A subclass whose __init__ requires an extra positional argument raises TypeError: __init__() missing 1 required positional argument: 'tag' at call time, not import time. The **kwargs forward above is the fix; without it, parametrize a test over every subclass × every alternate constructor.
  • A @dataclass subclass that adds a field without a default breaks the inherited classmethod at class-definition time: TypeError: non-default argument 'tag' follows default argument, because the generated __init__ orders non-default fields first.

Alternatives and when not to use this

ApproachBinds dynamic classSubclass inherits itUse when
classmethodyes (cls)yesnamed constructors, alternate input formats
staticmethodnono: must hard-codepure helper, no instance or class needed
__new__yes (cls)yesimmutable types, caching, returning an existing instance

__new__ also gets cls, but it changes construction for every caller and interacts awkwardly with __init__ running afterwards. A module-level factory function loses the cls binding entirely, so it can't be polymorphic. functools.singledispatchmethod dispatches on argument type and is worth it when the input format varies, but it does not solve the subclass-signature problem: you still need the **kwargs forward or compatible signatures.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Explain bound-method creation and the role of the descriptor protocol.

Answer

Core answer. A function stored on a class is a descriptor. obj.method does not return the function; it calls type(obj).__dict__['method'].__get__(obj, type(obj)), and FunctionType.__get__ returns a new method object holding __func__ (the function) and __self__ (the instance). Class.method returns the plain function, because __get__ is called with obj=None. That is the whole of "binding": no copying, no per-instance function, just a descriptor call at attribute-access time.

The descriptor protocol. object.__getattribute__ resolves obj.name in this order:

  1. name found on type(obj).__mro__ and it defines __set__ or __delete__ (a data descriptor) → call __get__(obj, type(obj)).
  2. Otherwise name in obj.__dict__ → return it.
  3. Otherwise the class attribute defines __get__ (a non-data descriptor) → call it.
  4. Otherwise return the class attribute.
  5. Otherwise __getattr__.

Functions define only __get__, so they are non-data descriptors: an instance attribute of the same name shadows the method. property, classmethod and staticmethod are descriptors too; property defines __set__, so it is a data descriptor and wins over the instance dict.

Python
class Counter:
    def __init__(self, n): self.n = n
    def bump(self, by=1):
        self.n += by
        return self.n

c = Counter(0)
m = c.bump
print(m.__self__ is c, m.__func__ is Counter.bump)
print(c.bump is c.bump, c.bump == c.bump)
print(Counter.bump(c, 5))

Trace (CPython 3.12):

  • c.bump → Counter.__dict__['bump'].__get__(c, Counter) → method with __self__ = c, __func__ = Counter.bump. Line 1 prints True True.
  • Each access builds a fresh method object, so is is False; method.__eq__ compares __func__ and __self__, so == is True. Line 2 prints False True.
  • Counter.bump is the function itself; __get__ with obj=None returns it unchanged. Counter.bump(c, 5) takes c.n from 0 to 5 and prints 5.
class attribute__get__(obj, cls) returnsdata descriptor?
plain functionbound method (__self__ = obj)no
staticmethodthe function, unboundno
classmethodmethod with __self__ = clsno
propertyresult of the getteryes

Alternatives and when not to use. functools.partial(f, obj) gives a callable with the argument pre-filled but no __self__, no __name__, and no descriptor behaviour: use it when you want a callback, not a method. Use staticmethod when the function genuinely does not need the instance. Write a custom descriptor only when you need per-attribute logic (validation, caching, lazy init); for one-off binding, a closure or partial is less machinery.

Failure modes.

  • Shadowing: self.bump = 5 puts bump in the instance dict; the non-data descriptor loses, and c.bump() raises TypeError: 'int' object is not callable. Any test that calls the method after assignment catches it.
  • Retention: a bound method holds a strong reference to __self__. Caching obj.method in a module-level dict keeps every instance alive; the leak shows up as flat memory in a heap profile.
  • Pickling: bound methods are picklable from Python 3.5, but they reduce to getattr(__self__, name), so pickling one pickles the instance too.
  • super(): super(C, self).bump re-runs the same __get__ with obj=self on the next class in the MRO. It is descriptor lookup, not a copy of the parent function.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Explain why implicit special-method lookup differs from ordinary attribute access.

Answer

What a strong candidate says first

len(x), x + y, x[i], for loops, with blocks and hash(x) do not go through x.__dict__. The interpreter resolves them on type(x), and for most of them, not even through a Python-level attribute lookup at all. CPython fills C-level slots on the type object when the class is created, and the bytecode calls those slots directly. Instance attributes are invisible to that path by construction.

The mechanism

When a class is created, type.__new__ runs fixup_slot_dispatchers, which for each special method looks it up in the new type's MRO and writes a function pointer into the corresponding slot of the type's tp_* structs. __len__ fills tp_as_sequence->sq_length; __add__ fills tp_as_number->nb_add; __getitem__ fills mp_subscript; __hash__ fills tp_hash; __call__ fills tp_call; __iter__ fills tp_iter. len(x) compiles to CALL on the builtin, which calls PyObject_Size, which reads Py_TYPE(x)->tp_as_sequence->sq_length and invokes it. No dict is consulted, so x.__len__ = ... cannot be seen.

A second family (__enter__, __exit__, __format__, __aenter__, __aexit__, __index__ in some paths) goes through _PyObject_LookupSpecial, which does _PyType_Lookup(Py_TYPE(obj), name) and then calls the descriptor's __get__. It still skips the instance dict and skips an instance-level __getattribute__ override.

Ordinary x.attr is different: type(x).__getattribute__ checks a data descriptor on the type, then x.__dict__, then a non-data descriptor or class attribute. Instance dict wins over non-data descriptors. That ordering is exactly what special lookup bypasses.

Worked trace

Python
class C:
    def __len__(self):
        return 3

c = C()
c.__len__ = lambda: 99

print(len(c))               # 3
print(c.__len__())          # 99
print(type(c).__len__(c))   # 3

Step by step: len(c) → PyObject_Size(c) → Py_TYPE(c)->tp_as_sequence->sq_length → slot_sq_length → C.__len__(c) → 3. The instance dict is never read. c.__len__() → type(c).__getattribute__(c, '__len__') → no data descriptor named __len__ on C → instance dict has the lambda → 99.

Class-level patching does take effect, because type.__setattr__ re-runs fixup_slot_dispatchers:

Python
C.__len__ = lambda self: 7
print(len(c))   # 7

And an instance-level __getattribute__ override is bypassed too:

Python
class D:
    def __len__(self): return 1
    def __getattribute__(self, name):
        if name == '__len__':
            return lambda: 42
        return object.__getattribute__(self, name)

d = D()
print(len(d))        # 1
print(d.__len__())   # 42

Why it is designed this way

Slots make len, +, [] and hash a single pointer dereference plus a C call, with no dict probe and no Python frame for the lookup itself. That is the reason list.__len__ is O(1) and len on a builtin is a few nanoseconds. It also makes the protocol contract enforceable: a class either fills the slot or it does not, so len(x) raises TypeError deterministically rather than depending on what happens to be in x.__dict__ at call time.

Trade-offs and when it bites

  • Per-instance mocking. unittest.mock.patch.object(instance, '__len__') silently does nothing for len(). Patch the class, or use patch.object(type(instance), '__len__').
  • __getattr__ fallbacks. A __getattr__ that synthesizes __iter__ or __getitem__ will not make for or [] work; the slot was already fixed at class creation.
  • Descriptors on the type. A descriptor assigned to the class does work for _PyObject_LookupSpecial paths, because the descriptor's __get__ is called. It does not work for pure slot paths like len unless the slot wrapper routes through it.
  • Metaclass __getattribute__. Overriding it on the metaclass does not intercept len(x); only type(x).__len__ matters.

Failure modes and detection

  • Silent no-op mock. Symptom: a test asserts len(obj) == 5 after patching the instance and still sees the real value. Detect by asserting on type(obj).__len__ in the test, or by using patch.object(type(obj), ...).
  • __getattr__-based protocol. Symptom: iter(obj) raises TypeError even though obj.__iter__ returns an iterator. Detect with a direct iter(obj) call in a unit test, not just obj.__iter__().
  • Pickle/copy divergence. __reduce__, __getstate__, __setstate__ are looked up on the type, so an instance-level override is ignored by pickle.dumps. Detect by round-tripping through pickle.loads(pickle.dumps(obj)) and comparing state.

What to say if pushed

If the interviewer asks why not just use __getattribute__ for everything: because the slot dispatch is what makes the protocol fast and unambiguous, and because __getattribute__ is itself a slot (tp_getattro) that would have to be consulted for every operation, including the ones used to implement __getattribute__. The split is deliberate: ordinary attribute access is customizable, protocol dispatch is not, and the boundary is the type object.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Use descriptor precedence to explain property behavior and API design.

Answer

Assume CPython 3.11+; the descriptor protocol is unchanged in 3.12. A property is a data descriptor: it defines __set__ and __delete__ even when you pass no setter. Descriptor precedence is the rule that object.__getattribute__ checks the type's MRO for a data descriptor before it looks in the instance __dict__. Non-data descriptors (plain functions, classmethod, staticmethod) define only __get__, so the instance dict wins over them. That one ordering explains property behavior and most API design rules around it.

Lookup order for obj.x:

StepCheckResult
1data descriptor in type(obj).__mro__call __get__(obj, type(obj))
2obj.__dict__['x']return that value
3non-data descriptor or class attributecall __get__ or return class value
4__getattr__fallback only if steps 1–3 miss

Assignment uses the same precedence: object.__setattr__ looks for a data descriptor on the type and calls its __set__; otherwise it writes obj.__dict__.

Python
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("below absolute zero")
        self._celsius = value

t = Temperature(20)
t.__dict__["celsius"] = 999   # bypasses the setter
print(t.celsius)              # 20

Trace: t.celsius finds the celsius property in Temperature.__mro__. Because property is a data descriptor, step 1 wins over the instance dict. __get__ returns _celsius, which is 20. The 999 is ignored. t.celsius = 25 calls the property's __set__, validates, and writes _celsius. The stale celsius: 999 remains in __dict__ but never affects reads. inspect.getattr_static(t, "celsius") returns the property object, which is how you detect this in a debugger.

Contrast a method, which is a non-data descriptor:

Python
class C:
    def m(self):
        return "method"

c = C()
c.__dict__["m"] = lambda: "instance"
print(c.m())  # instance

Because m is a function, it defines only __get__. Step 2 beats step 3, so the instance attribute shadows the method. That is why per-instance overrides work, and why accidentally assigning obj.method = something silently changes call sites.

API design follows from the precedence. Use a property when access is cheap, idempotent, and attribute-like: validation, derived values, lazy initialization with caching. Use an explicit method when the operation is expensive, fallible, or side-effecting. If row.total sums a 10,000-element list, a loop over 1,000 rows does 10^7 additions instead of 10^4 if you cache once. Callers put properties in loops, logs, and debuggers; they do not expect I/O or mutation there.

Failure modes to name in review: a property without a setter raises AttributeError: property 'x' of 'C' object has no setter on assignment, but reads still work; a property that mutates state on read fires during logging; a property that hides a network call turns obj.user into a p99 latency source. __slots__ creates data descriptors per slot, so slots win over instance dict and remove __dict__ entirely: good for memory, bad if callers rely on dynamic attributes. Detect precedence surprises with inspect.getattr_static, type(obj).__mro__, and obj.__dict__; profile repeated property access with cProfile or timeit before deciding it is cheap.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Explain C3 method resolution in a diamond hierarchy.

Answer

Core answer. Python linearizes every class into one ordered list, Cls.__mro__, using the C3 algorithm. For a diamond where D(B, C) and both B and C inherit from A, the order is D, B, C, A, object: left parent, then right parent, then the shared base once. The key consequence: super() does not mean "my parent". It means "the next class after me in the MRO of the instance's type", which is why cooperative super() calls walk the diamond exactly once instead of visiting A twice.

The mechanism. C3 computes L(C) = C + merge(L(base1), L(base2), ..., [base1, base2, ...]). merge repeatedly takes the head of the first list that appears in no other list's tail; if no such head exists, the hierarchy is inconsistent and Python raises TypeError at class-creation time. Two invariants fall out: local precedence (bases keep their declared left-to-right order) and monotonicity (a class's relative order is preserved in every subclass).

Worked diamond.

Python
class A:
    def greet(self): return "A"
class B(A):
    def greet(self): return "B->" + super().greet()
class C(A):
    def greet(self): return "C->" + super().greet()
class D(B, C):
    pass

print([c.__name__ for c in D.__mro__])
print(D().greet())

Trace of the merge: L(B) = [B, A, object], L(C) = [C, A, object]. merge([B,A,object], [C,A,object], [B,C]) takes B (head of the first list, in no tail), skips A (it sits in the tail of the second list), takes C, then A, then object. Output:

['D', 'B', 'C', 'A', 'object']
B->C->A

D().greet() dispatches to B.greet; its super() resolves to C, not A, so C.greet runs, and its super() finally reaches A. Each class in the chain runs once.

When C3 refuses. Ordering constraints can be unsatisfiable:

Python
class X: pass
class Y: pass
class A(X, Y): pass
class B(Y, X): pass
class C(A, B): pass

TypeError: Cannot create a consistent method resolution order (MRO) for bases X, Y. A demands X before Y; B demands the reverse; no linearization satisfies both.

Trade-offs. A naive depth-first left-to-right search would give D, B, A, C, object for the diamond, putting A before C and silently discarding C's overrides. C3 keeps A last, which is what makes cooperative multiple inheritance work. The cost is that C3 is stricter: hierarchies that "look fine" can be rejected outright. If you need a base visited before a sibling, C3 will not let you express it.

Failure modes. (1) Non-cooperative __init__: if B.__init__ calls super().__init__() but C.__init__ does not, A.__init__ never runs. Detect with an assertion inside A.__init__ or by printing D.__mro__ and checking each class's __init__. (2) super() used where no __class__ cell exists (e.g. inside a nested function defined outside the class body) raises RuntimeError: super(): __class__ cell not found. (3) Assuming super() means the literal parent: from a D instance, super(B, self) yields C, not A. C3 has been Python's linearization since 2.3.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe the contract required for cooperative `super()` calls.

Answer

The contract, in one breath. Cooperative super() is a protocol, not a lookup shortcut. Every class in the MRO that participates agrees to four things:

  1. Call super().method(...) exactly once, or deliberately not at all, which ends the chain.
  2. Accept the arguments the chain hands you and forward everything you do not consume.
  3. Consume only the parameters you own; pass the rest through unchanged.
  4. Let the chain terminate at a method that accepts the residual arguments: normally object, which accepts none.

Mechanism. Zero-argument super() is compiled to super(__class__, <first argument>), where __class__ is a closure cell holding the class whose body the method was defined in. super(C, obj) returns a proxy that searches type(obj).__mro__ starting immediately after C. The anchor is the defining class, not the runtime class: that is why identical source behaves differently under different MROs, and why the chain is linearized by C3 rather than by lexical nesting.

Python
class Base:
    def __init__(self, **kwargs):
        super().__init__(**kwargs)          # terminates at object

class Logged:
    def __init__(self, *, log=None, **kwargs):
        self.log = log
        super().__init__(**kwargs)

class Timestamped:
    def __init__(self, *, ts=None, **kwargs):
        self.ts = ts
        super().__init__(**kwargs)

class Record(Logged, Timestamped, Base):
    def __init__(self, name, **kwargs):
        self.name = name
        super().__init__(**kwargs)

MRO: Record → Logged → Timestamped → Base → object.

Trace Record("r", log=print, ts=1):

  • Record.__init__ sets name, forwards log=print, ts=1.
  • Logged.__init__ consumes log, forwards ts=1.
  • Timestamped.__init__ consumes ts, forwards nothing.
  • Base.__init__ forwards nothing to object.__init__(), which accepts no extra arguments.

Result: r.name == "r", r.log is print, r.ts == 1.

What breaks when the contract is violated.

BreakSymptomDetection
A class omits **kwargsTypeError: Timestamped.__init__() got an unexpected keyword argument 'log'Construct the class with every mixin present
Residual kwargs reach objectTypeError: object.__init__() takes exactly one argument (the instance to initialize)Same construction test
Zero-arg super() in a nested function or staticmethodRuntimeError: super(): no argumentsReview; the zero-arg form needs the instance as first positional argument
A class forgets super()No error at all: downstream mixins never initializeAssert the attributes they set exist
super() called twiceDuplicated side effectsCount calls against a test double

Trade-offs. Cooperative super() couples every class in the MRO to one shared signature: adding a mixin can change which arguments reach a class that never knew about it. A mixin that never needs to cooperate, or a single-inheritance hierarchy, is clearer with an explicit Parent.method(self) and no **kwargs plumbing. Note also that __init_subclass__ and __set_name__ are implicit class-creation hooks: they are not part of the super() chain and do not participate in this contract.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

How should initialization work across a multiple-inheritance hierarchy?

Answer

Core answer. In Python 3, initialization across a multiple-inheritance hierarchy works only if every class in the chain cooperates. Each __init__ takes **kwargs, pops the arguments it owns, and calls super().__init__(**kwargs) with the remainder. The chain terminates at object.__init__(), which accepts no extra arguments. Never call a base initializer by name, Base.__init__(self, ...), because that bypasses the MRO and either skips a base or runs shared ancestry twice.

Assumption: you control every class in the hierarchy and can give them a shared keyword protocol. If you can't, use composition.

Why it works. super() is not "the parent class"; it is "the next class after the current one in type(self).__mro__". Python computes the MRO with C3 linearization, which preserves local precedence order and monotonicity. For class D(B, C) where B and C both inherit A, the MRO is D, B, C, A, object. So super().__init__ inside B calls C.__init__, not A.__init__. That is the whole trick: each class hands the remaining keyword arguments to whoever is next, and A runs exactly once, after both B and C.

Python
class A:
    def __init__(self, **kwargs):
        self.a = kwargs.pop('a', 0)
        super().__init__(**kwargs)

class B(A):
    def __init__(self, **kwargs):
        self.b = kwargs.pop('b', 0)
        super().__init__(**kwargs)

class C(A):
    def __init__(self, **kwargs):
        self.c = kwargs.pop('c', 0)
        super().__init__(**kwargs)

class D(B, C):
    def __init__(self, **kwargs):
        self.d = kwargs.pop('d', 0)
        super().__init__(**kwargs)

d = D(a=1, b=2, c=3, d=4)
print(D.__mro__)
print(d.a, d.b, d.c, d.d)

Trace, in call order:

  • D.__init__ pops d=4, calls super().__init__(a=1, b=2, c=3) → B
  • B.__init__ pops b=2, calls super().__init__(a=1, c=3) → C
  • C.__init__ pops c=3, calls super().__init__(a=1) → A
  • A.__init__ pops a=1, calls super().__init__() → object
  • object.__init__() with no extra args, returns.

Output:

(<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class 'object'>)
1 2 3 4

Failure modes and how to detect them.

  • Chain doesn't terminate. If any class forwards leftover kwargs to object.__init__, CPython raises TypeError: object.__init__() takes exactly one argument (the instance to initialize). Symptom: construction fails at the last class in the MRO. Fix: pop everything you own, or assert not kwargs before the final super().__init__().
  • Silent skip. A class that forgets super().__init__() stops the chain. A never runs, so d.a raises AttributeError later: often far from the constructor. Detect with a test that appends each class name to a list in __init__ and asserts the list equals the MRO order.
  • Double init. Calling A.__init__(self, ...) directly from both B and C runs A.__init__ twice in the diamond. Symptom: a counter reads 2, a file is opened twice, a list is appended twice. The same test catches it.
  • Typo swallowed. kwargs.pop('lable', 0) silently uses the default. Mitigate by not defaulting, or by asserting not kwargs at the end of the chain.

Trade-offs. Cooperative MI is the right call for mixins that add orthogonal behavior (logging, caching, retry) where each has a small, stable keyword contract and no independent lifecycle. Composition is the right call when the parts have conflicting constructor signatures, need to be swapped at runtime, or are owned by different teams. The cost of cooperative __init__ is that **kwargs erases the static signature: mypy cannot check that D(a=1) is valid. Where you can, use keyword-only parameters (def __init__(self, *, a=0, **kwargs)) so the common case is checked and only the forwarding path is dynamic.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Use substitutability to choose composition or inheritance.

Answer

Core answer. Substitutability is the test: can every consumer written against the base type accept the subtype without knowing it? If yes, inheritance is on the table; if no, compose. Inheritance buys the base's protocol and its obligations: every public method, every documented invariant, every constructor assumption. Composition buys only the behavior you delegate to, behind an interface you declare. Pick inheritance when the subtype honors the base's whole contract; otherwise hold the collaborator as an attribute and expose a narrower surface.

Assumptions: Python 3.12 on CPython, single inheritance unless noted.

Why inheritance breaks substitutability. A subclass is not just a code-reuse channel; it is a claim that isinstance(sub, Base) is safe. Three things ride along with that claim. The MRO decides which __init__ and which super() chain runs, so inserting a mixin changes construction. The base's public methods stay callable on the subtype whether or not the subtype's invariant survives them. And consumer code that does isinstance(x, Base) or catches Base will now match your object. Composition removes all three: the collaborator is a private attribute, and the only methods callable are the ones you wrote.

Worked example. A stack built by subclassing list:

Python
# Python 3.12
class Stack(list):
    def push(self, item):
        self.append(item)

s = Stack()
s.push("a")
s.push("b")
s.insert(0, "c")      # inherited list API, no error
print(list(s))        # ['c', 'a', 'b']
print(s.pop())        # 'b'
print(s.pop())        # 'a'
print(s.pop())        # 'c'

Trace: push("a") → ['a']; push("b") → ['a','b']; insert(0,"c") → ['c','a','b']. pop() removes the tail → 'b', leaving ['c','a']; next pop() → 'a', leaving ['c']; last pop() → 'c'. The stack drained b, a, c, not reverse push order, because insert put c at the bottom where pop cannot reach it in order. Nothing raised. list.insert(0, x) is O(n) (CPython memmoves the tail; at 10⁶ elements that is an 8 MB move on a 64-bit build), so the failure is also a silent performance cliff.

The composed version:

Python
class Stack:
    def __init__(self):
        self._items = []
    def push(self, item):
        self._items.append(item)
    def pop(self):
        return self._items.pop()
    def __len__(self):
        return len(self._items)

isinstance(Stack(), list) is now False, and s.insert raises AttributeError. The invariant "only the top is removable" is enforced by the absence of the method, not by documentation.

Decision criteria.

CriterionInheritanceComposition
Contract owedEvery base method and invariantOnly the methods you declare
CouplingBase __init__ signature, MRO, protected attrsOne constructor argument or attribute
Substitutability checkFull base test suite must pass on the subtypeStructural match against a Protocol
Cost of base changeSubtype breaks silentlyContained in the wrapper

Failure modes and detection. The classic defect is inheriting for reuse: you wanted append/pop and got insert, sort, __setitem__, __iadd__ as well. Detection is a property test: for any interleaving of push/pop, the drain order must be the reverse of push order. That test passes on the composed Stack and fails on Stack(list) the moment anything calls a list method. Static checkers will not catch it: mypy and pyright see a valid list subtype. A second failure mode is constructor coupling, if the base's __init__ gains a required parameter, every subclass breaks at import time.

When inheritance is right. When the subtype genuinely is the base and adds no weaker invariant: class Status(enum.IntEnum): OK = 200 is usable anywhere an int is expected, and that is the point. class HttpError(Exception) adds fields but keeps the raise/str() contract. If you want structural substitutability without the hierarchy, declare a typing.Protocol with push/pop and let the composed class satisfy it: consumers type against the protocol, and no base-class API leaks in.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Define a safe equality and hashing policy for a domain value object.

Answer

The 90-second version. Two rules decide the policy. First, __hash__ must be consistent with __eq__: if a == b then hash(a) == hash(b), or dict and set lookups silently miss. Second, a hash must not change while the object is a key, so every field that feeds __hash__ has to be immutable for the object's lifetime. The policy that follows: a value object is frozen and hashes exactly the fields that participate in equality; an entity keeps identity equality and identity hashing; a mutable value object is deliberately not hashable. Assume Python 3.11+ with dataclasses or attrs.

The decision rule. Hash the same fields __eq__ compares, and only those. In a dataclass that is the compare=True fields; mark mutable or derived fields compare=False so they drop out of both __eq__ and __hash__. If a compared field cannot be made immutable, the object is not a dict key: set __hash__ = None on purpose rather than hoping nobody mutates it.

Python
from dataclasses import dataclass

@dataclass(frozen=True)
class Money:
    amount: int      # minor units, e.g. cents
    currency: str    # ISO 4217

a = Money(1000, "USD")
b = Money(1000, "USD")
print(a == b, hash(a) == hash(b))   # True True

Trace: frozen=True, eq=True makes the dataclass generate __eq__ comparing (amount, currency) and __hash__ returning hash((self.amount, self.currency)). Both instances build the same tuple, so the hashes match and the objects are equal. attrs.define(frozen=True) behaves the same way; attrs.define without frozen sets __hash__ = None when eq=True, exactly like a plain dataclass.

Failure 1: frozen but unhashable field.

Python
@dataclass(frozen=True)
class Tag:
    labels: list[str]

t = Tag(["a"])   # constructs fine
hash(t)          # TypeError: unhashable type: 'list'

Trace: the generated __hash__ is hash((self.labels,)); hashing the tuple calls hash(["a"]), and list has no __hash__, so the TypeError fires at call time, not at class definition. Detection: call hash(t) or put t in a set inside a unit test.

Failure 2: mutation after hashing.

Python
@dataclass(unsafe_hash=True)
class Cache:
    key: str
    hits: int = 0

c = Cache("a")
d = {c: 1}
c.hits += 1
print(d[c])                 # KeyError
print(Cache("a", 0) in d)  # False

Trace: unsafe_hash=True forces __hash__ = hash((self.key, self.hits)). Insertion uses hash(("a", 0)). After c.hits += 1, lookup uses hash(("a", 1)), lands in a different bucket, and raises KeyError. The old entry is stranded: no live object hashes to its bucket, so it leaks and len(d) stays 1. Detection: insert into a set, mutate, assert membership; or make the class frozen=True so mutation raises FrozenInstanceError instead.

Failure 3: subclassing. Defining __eq__ in a subclass sets __hash__ = None on that subclass even when the parent was hashable, so a hashable base plus a subclass that adds __eq__ becomes unhashable. Detection: hash(instance) in the subclass's own tests.

design__eq____hash__use when
@dataclass(frozen=True)compared fieldssame fieldsvalue object, all compared fields immutable
@dataclasscompared fieldsNonemutable value object, never a key
@dataclass(unsafe_hash=True)compared fieldssame fieldsonly if you can prove no post-hash mutation
plain class (entity)identityid()lifecycle object with mutable state
NamedTupletupletuplesmall immutable record; unhashable field raises TypeError

Cross-process note. Since Python 3.3, str and bytes hashing is randomized per process via PYTHONHASHSEED, so never persist a hash or compare hashes across processes: persist the value or a stable digest such as hashlib.sha256.

So the policy in one line: freeze the value object, hash exactly the equality fields, exclude mutable ones, and if you cannot, do not hash it at all. Entities keep identity hashing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Design symmetric cross-type equality using `NotImplemented`.

Answer

The rule. __eq__ returns True or False only when it fully understands the other operand. For any type it doesn't recognize, it returns NotImplemented: a singleton sentinel, not an exception, and truthy if you accidentally use it in a boolean context. Returning it hands control back to the interpreter: Python then calls the reflected method type(other).__eq__(other, self), and only if that also returns NotImplemented does it fall back to identity (self is other). != is derived from __eq__ in Python 3, so you rarely define __ne__.

Assumptions: you own both types (or they cooperate), you want value equality across two representations of the same quantity, and you control __hash__.

Worked design. Two temperature types that should compare equal across scales.

Python
class Celsius:
    def __init__(self, deg): self.deg = deg
    def __eq__(self, other):
        if isinstance(other, Celsius):
            return self.deg == other.deg
        if isinstance(other, Fahrenheit):
            return self.deg == (other.deg - 32) * 5 / 9
        return NotImplemented
    def __hash__(self):
        return hash(("temp", self.deg))

class Fahrenheit:
    def __init__(self, deg): self.deg = deg
    def __eq__(self, other):
        if isinstance(other, Fahrenheit):
            return self.deg == other.deg
        return NotImplemented          # not False
    def __hash__(self):
        return hash(("temp", (self.deg - 32) * 5 / 9))

Trace. Celsius(100) == Fahrenheit(212):

  • Celsius.__eq__(Celsius(100), Fahrenheit(212)) → matches the Fahrenheit branch → 100 == (212-32)*5/9 → 100 == 100.0 → True.

Fahrenheit(212) == Celsius(100):

  • Fahrenheit.__eq__(Fahrenheit(212), Celsius(100)) → not a Fahrenheit → NotImplemented.
  • Interpreter tries reflected Celsius.__eq__(Celsius(100), Fahrenheit(212)) → True.

Both directions agree. Now change that return NotImplemented to return False:

  • Fahrenheit(212) == Celsius(100) → False immediately, no reflected call.
  • Celsius(100) == Fahrenheit(212) → still True.

a == b is True while b == a is False: symmetry broken, and set/dict membership becomes order-dependent.

Alternatives.

choiceeffect
NotImplementedinterpreter tries reflected method, then identity fallback
Falseshort-circuits; breaks symmetry when the other type would have matched
raise TypeErroraborts the comparison; == is expected to be total, so this surprises callers and breaks in
convert other to your typeworks only if the conversion is lossless and you own the semantics; silently wrong for unrelated types

Hash. Defining __eq__ sets __hash__ to None, so you must redefine it. Equal objects must hash equal, so cross-type equality forces a shared canonical hash: here both hash on Celsius degrees. Without that, Celsius(100) and Fahrenheit(212) land in different dict buckets despite being equal.

When not to. If a type only ever compares to itself, returning False for everything else is fine and cheaper: there is no reflected partner to defer to. Return NotImplemented specifically when another type might know the answer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

When, if ever, is `unsafe_hash` defensible?

Answer

Short answer. unsafe_hash=True is defensible in one shape: every field that participates in __eq__ is logically immutable, but you cannot mark the class frozen=True, because it inherits from a non-frozen base, or it carries a mutable non-compared cache field, or __post_init__ sets derived state. Then it gives value-based hashing without freezing the whole object. Everywhere else it is a bug waiting to happen: if any compared field can change after the object is used as a dict key or set member, the entry becomes unreachable.

Mechanism. @dataclass decides __hash__ from eq and frozen (defaults eq=True, frozen=False):

  • eq=True, frozen=False → __hash__ is set to None; instances are unhashable. This is the default, and it is why you hit TypeError: unhashable type.
  • eq=True, frozen=True → a __hash__ is generated as hash((f1, f2, ...)) over the fields with compare=True (or hash=True).
  • eq=False → __hash__ is left untouched, so you get object's id-based hash.
  • unsafe_hash=True → forces the generated field-based __hash__ even when frozen=False. It does not make the object immutable; it only asserts you will keep the compared fields fixed.

So unsafe_hash is not a hashing feature; it is an assertion that the compared fields are stable.

Worked trace.

Python
from dataclasses import dataclass

@dataclass(unsafe_hash=True)
class Point:
    x: int
    y: int

p = Point(1, 2)
d = {p: "v"}
p.x = 99
print(p in d)              # False
print(d.get(Point(1, 2)))  # None
print(len(d))              # 1

Step by step: Point(1,2) hashes to hash((1,2)) and is stored in that bucket. p.x = 99 rewrites the field, so hash(p) is now hash((99,2)). p in d hashes to the new bucket, finds nothing, returns False. d.get(Point(1,2)) hashes to the old bucket, finds the stored key, compares Point(1,2) == Point(99,2) → False, returns None. The value "v" is still in the dict, len(d) is 1, but no key reaches it. That is the leak: silent, no exception, memory retained.

Alternatives and when to pick them.

optionuse whencost
frozen=Trueobject is genuinely immutable__setattr__ raises FrozenInstanceError; can't inherit from a non-frozen base
eq=Falseidentity is the real key (mutable, long-lived)no value equality; == is is
custom __hash__you want to hash a stable subset explicitlyyou own consistency with __eq__
unsafe_hash=Truecompared fields are stable but the class can't be frozenyou own the invariant; nothing enforces it

Failure modes and detection. The failure is a key that stops matching after mutation: key in d flips to False while len(d) is unchanged, and d[key] raises KeyError for a key you inserted. Detect it with a test that inserts, mutates a compared field, and asserts membership, or, better, make the compared fields read-only so the mutation cannot happen. If you must keep unsafe_hash, mark every mutable field field(compare=False) so it never enters the hash.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

What does a dataclass generate, and which domain concerns remain manual?

Answer

@dataclass is a code generator, not a validator. It reads the class's annotated fields and writes methods into the class body. Nothing about the values is checked at runtime.

What it generates (Python 3.7+, PEP 557; slots, kw_only and __match_args__ arrive in 3.10):

MethodGenerated whenBehaviour
__init__init=True (default)assigns each field from a parameter
__repr__repr=True (default)ClassName(field=value, ...)
__eq__eq=True (default)compares field tuples; returns NotImplemented for a different class
__lt__, __le__, __gt__, __ge__order=Truetuple comparison; raises ValueError if eq=False
__hash__frozen=True and eq=Truehash(field_tuple)
__hash__ = Noneeq=True, frozen=Falseinstances become unhashable
__match_args__always (3.10+)field names for match

field() controls per-field behaviour: default_factory, init=False, repr=False, compare=False, hash=False.

Worked trace.

Python
from dataclasses import dataclass, field

@dataclass(order=True)
class Money:
    amount: int
    currency: str = "USD"
    _cache: dict = field(default_factory=dict, init=False, repr=False, compare=False)

Money(5) → amount=5, currency='USD', _cache={}. repr → Money(amount=5, currency='USD'): _cache omitted. Money(5) == Money(5, "USD") → (5,'USD') == (5,'USD') → True. Money(5) < Money(10) → (5,'USD') < (10,'USD') → True. hash(Money(5)) → TypeError: unhashable type: 'Money', because eq=True with frozen=False sets __hash__ = None.

What stays manual. Type annotations are not enforced: Money("five") constructs fine. No validation, no serialization, no to_dict/from_dict, no deep immutability (frozen=True blocks rebinding, not mutation of a list field), no cross-field invariants.

Failure modes and detection.

  • Mutable default: items: list = [] raises ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory at import.
  • Unhashable: using a non-frozen dataclass as a dict key raises TypeError at runtime; fix with frozen=True, eq=False, or unsafe_hash=True.
  • Secret leakage: a token field with default repr=True prints in logs; set repr=False.
  • Inheritance: a subclass adding a defaulted field after a base field without a default raises TypeError: non-default argument follows default argument.

Alternatives. NamedTuple: immutable, tuple-indexable, but no default_factory and no validators. attrs: validators, converters, slots by default. pydantic: runtime validation and serialization at the boundary. Plain class: full control, no generation.

Pick dataclass when the type is a data holder and invariants are enforced by the caller. Pick pydantic when untrusted input crosses a boundary. Pick attrs when you want validators without pydantic's coercion.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Why is `default_factory` the correct tool for mutable dataclass defaults?

Answer

The 90-second answer. A dataclass field default is a single object, created once when the class body executes and stored on the class. __init__ assigns that same object to every instance that doesn't pass a value. For an immutable default (0, "", None, ()) sharing is harmless. For a mutable one it's a bug: every instance aliases one list. default_factory fixes this by storing a zero-argument callable instead of a value and calling it inside __init__ for each new instance, so each gets a fresh object. Python 3.7+ (PEP 557) also refuses the naive default=[] outright, so the factory isn't merely better: it's the only spelling that works.

Mechanism.

Python
from dataclasses import dataclass, field

@dataclass
class Cart:
    items: list = field(default_factory=list)
    tags: set = field(default_factory=set)

The generated __init__ is equivalent to:

Python
_HAS_DEFAULT_FACTORY = ...  # sentinel

def __init__(self, items=_HAS_DEFAULT_FACTORY, tags=_HAS_DEFAULT_FACTORY):
    if items is _HAS_DEFAULT_FACTORY:
        items = list()          # factory called here, per instance
    self.items = items
    if tags is _HAS_DEFAULT_FACTORY:
        tags = set()
    self.tags = tags

Trace it:

Python
a = Cart()
b = Cart()
a.items.append("book")
a.items            # ['book']
b.items            # []
a.items is b.items # False

Each Cart() call hits list() once. Two instances, two lists. With default=[] the class definition itself fails:

Python
@dataclass
class Bad:
    items: list = []
# ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory

The check is unhashability, not mutability. CPython's _get_field raises when f.default.__class__.__hash__ is None. list, dict and set are unhashable, so they're caught. A custom mutable class with the default identity hash is not caught and will silently alias:

Python
class Box:
    def __init__(self): self.v = []

@dataclass
class Holder:
    box: Box = Box()   # accepted, and shared by every Holder

h1, h2 = Holder(), Holder()
h1.box.v.append(1)
h2.box.v   # [1]  -- aliased

So "use default_factory for mutable defaults" is broader than what the interpreter enforces.

Alternatives and when to use them.

ApproachUse whenCost
default=() / frozenset() / Nonedefault is immutablenone; no per-instance call
field(default_factory=...)fresh mutable per instanceone call per instance per field
__post_init__default derived from other fieldsruns after __init__; needs object.__setattr__ under frozen=True
InitVarvalue passed in, then consumed in __post_init__not a stored field

default_factory is zero-argument, so it can't see sibling fields: that's exactly when you drop to __post_init__.

Failure modes. (1) Aliasing: symptom is a mutation on one instance appearing on another; detect with assert a.items is not b.items or a two-instance test. (2) default_factory=[], passing an object instead of a callable, fails at construction with TypeError: 'list' object is not callable, not at class definition. (3) Late-binding closure: field(default_factory=lambda: [i]) inside a loop captures the loop variable; bind it with a default argument or a named function. (4) The hashable-mutable case above, which no error catches.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How do inherited defaults and keyword-only fields affect dataclass constructors?

Answer

The short answer

@dataclass flattens the hierarchy into one field list before it generates __init__: it walks the MRO from the base-most class down, copies each base's __dataclass_fields__ in order, then appends the class's own annotated fields in definition order. Inherited fields therefore come first, as positional parameters. Two consequences:

  • A positional field with no default cannot follow a positional field that has one. Violating this raises TypeError when the class statement executes, not when you instantiate.
  • Keyword-only fields (Python 3.10+) are exempt from that ordering rule and are emitted after * in the signature.

So an inherited default forces every later positional field in a subclass to carry a default too; keyword-only is the escape hatch that lets a subclass add a required field without touching the base.

Why: the field list is built base-first

Python
from dataclasses import dataclass

@dataclass
class Base:
    x: int = 0

@dataclass
class Sub(Base):
    y: int          # no default

Processing Sub: Sub.__mro__[-1:0:-1] is (object, Base). object has no __dataclass_fields__; Base contributes x (default 0). Then Sub's own annotation adds y. Effective order: x, y. The __init__ builder walks the positional fields, records x as the first defaulted field, then hits y with no default and raises TypeError naming y. The traceback points at the class Sub(Base): line: nothing is instantiated.

A base that is not itself a @dataclass contributes no fields, so this only triggers when the base was decorated.

The keyword-only fix

Python
from dataclasses import dataclass, field

@dataclass
class Base:
    x: int = 0

@dataclass
class Sub(Base):
    y: int = field(kw_only=True)

Sub(1, y=2)   # Sub(x=1, y=2)
Sub(y=2)      # Sub(x=0, y=2)
Sub(1, 2)     # TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

Generated signature: def __init__(self, x=0, *, y). The ordering check only inspects non-keyword-only fields, so y is skipped and the class defines cleanly.

Three ways to get the same signature (all 3.10+):

DeclarationEffect
field(kw_only=True) on one fieldThat field moves after *
@dataclass(kw_only=True) on the subclassEvery field declared in that class becomes keyword-only; inherited fields keep their own setting
_: KW_ONLY sentinelEvery field after it in that class becomes keyword-only

Trade-offs and traps

  • kw_only=True is the right fix when you must add a required field to a subclass and cannot reorder the base. Cost: callers lose positional access to that field, and it needs 3.10+.
  • Reordering the base so required fields come first works on any version but breaks every existing positional call site.
  • Removing the base default also works but breaks callers relying on it.
  • default_factory counts as a default for the ordering check, so switching default=[] to default_factory=list does not relax it.
  • Re-declaring an inherited field name in a subclass keeps the base's position in the list but takes the new default and type.
  • init=False fields are excluded from __init__ and from the ordering check; ClassVar annotations are not fields at all.
  • A subclass that forgets @dataclass gets no generated __init__ and no error: its annotations stay plain annotations.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Differentiate `ClassVar`, `InitVar`, and ordinary dataclass fields.

Answer

What a strong candidate says first

@dataclass classifies every annotation in __annotations__ into one of three buckets, and the bucket decides four things: whether the name is an __init__ parameter, whether it is stored on the instance, and whether it shows up in fields(), __repr__ and __eq__.

  • Ordinary field: yes to all four.
  • ClassVar[T]: no to all four. It is skipped before a Field is even created, so it stays a plain class attribute.
  • InitVar[T]: an __init__ parameter only. Its value is handed to __post_init__ and then dropped. Not stored, not in fields(), not in __repr__, not in __eq__.
Python
from dataclasses import dataclass, fields, InitVar
from typing import ClassVar

@dataclass
class Job:
    name: str
    retries: int = 3
    registry: ClassVar[dict] = {}   # class-level, shared by every instance
    secret: InitVar[str] = ""       # init-only, never stored

    def __post_init__(self, secret):
        self.token = hash(secret)

Traced on CPython 3.12:

  • fields(Job) → (Field(name='name'), Field(name='retries')). registry and secret are absent.
  • Job("a", secret="pw") → name='a', retries=3, token=hash("pw"). There is no secret attribute; Job("a", secret="pw").secret raises AttributeError.
  • repr(Job("a", secret="pw")) → Job(name='a', retries=3).
  • Job("a", secret="pw") == Job("a", secret="other") → True; __eq__ compares only (name, retries).
  • Job("a").registry is Job("b").registry → True; both read the same class dict.

Why it behaves that way. _process_class walks the annotations and calls _is_classvar and _is_initvar on each. A ClassVar hits continue before any Field exists. An InitVar becomes a Field with _field_type = _FIELD_INITVAR. _init_fn includes both _FIELD and _FIELD_INITVAR in the generated signature and appends the InitVar values to the __post_init__ call, while _repr_fn, _cmp_fn and fields() filter down to _FIELD only. That single filter is what makes InitVar a pseudo-field.

ClassVarInitVarordinary field
__init__ parameternoyesyes
stored on instancenonoyes
in fields()nonoyes
in __repr__nonoyes
in __eq__nonoyes
passed to __post_init__noyesno

Failure modes.

  1. Mutable ClassVar shared across instances. registry: ClassVar[dict] = {} means Job("a").registry["k"] = 1 is visible from every instance and from the class. A test asserting Job("a").registry is not Job("b").registry fails. Fix: make it an ordinary field with field(default_factory=dict), or keep the ClassVar immutable.
  2. InitVar silently dropped when __post_init__ is missing or misspelled. Job("a", secret="pw") constructs fine and token never exists. Detected by asserting the derived attribute is present.
  3. InitVar counts toward __init__ argument ordering. A base dataclass with secret: InitVar[str] = "" plus a subclass field without a default raises TypeError: non-default argument 'x' follows default argument at class-definition time.
  4. InitVar is excluded from __eq__ while still driving stored state. Two Jobs with different secrets have different token but compare equal: a broken equality contract if callers rely on ==.

Choosing between them. ClassVar for shared constants, registries, caches and type-level config. InitVar for a value consumed once at construction and deliberately not retained: a password hashed into token, a raw string normalized into a stored form. Ordinary field for anything that is part of the object's state and identity. If you need the value after construction but not in repr or ==, use field(repr=False, compare=False) rather than InitVar.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

How would you use `__post_init__` without hiding dangerous construction side effects?

Answer

Core answer (say this first). Treat __post_init__ as a pure function of the already-assigned fields: derive computed fields, validate cross-field invariants, raise. Never do I/O, registration, or anything with an effect a caller can't see from the constructor call. When construction genuinely needs a side effect, put it behind a named classmethod factory, so Client(...) stays cheap and Client.connect(...) is greppable in review and in a profiler.

Mechanism. The @dataclass decorator generates __init__, which assigns fields in declaration order and then calls self.__post_init__(), passing any InitVar values as positional arguments in declaration order. Two consequences decide the design. InitVar fields are not stored as attributes: they exist only to reach __post_init__. And if you define your own __init__, the decorator does not generate one and does not call __post_init__; you must call it yourself, or your invariants silently stop running.

Python
from dataclasses import dataclass, field, InitVar

@dataclass(frozen=True)
class Temperature:
    celsius: float
    scale: InitVar[str] = "C"
    fahrenheit: float = field(init=False)

    def __post_init__(self):
        if self.scale not in ("C", "F"):
            raise ValueError(f"unknown scale {self.scale!r}")
        object.__setattr__(self, "fahrenheit", self.celsius * 9 / 5 + 32)

Trace Temperature(100): the generated __init__ sets celsius=100 (through object.__setattr__, because frozen=True), skips fahrenheit (init=False), then calls __post_init__("C"). The check passes; object.__setattr__ writes fahrenheit = 100*9/5+32 = 212.0. So Temperature(100).fahrenheit is 212.0. Temperature(100, "K") raises ValueError: unknown scale 'K' before fahrenheit is written.

The dangerous version. Same shape, but the effect is a socket:

Python
@dataclass
class Client:
    host: str
    port: int = 5432
    conn: object = field(init=False, default=None)

    def __post_init__(self):
        self.conn = socket.create_connection((self.host, self.port), timeout=5)

Now every construction opens a TCP connection. dataclasses.replace(client, port=5433) builds a new instance through __init__, so it opens a second connection and the first is never closed. A comprehension over 50 hosts opens 50 sockets with no obvious call site. A test that only wants to check client.host pays a 5-second timeout when the host is down.

The fix: name the effect.

Python
@dataclass
class Client:
    host: str
    port: int = 5432
    conn: object = field(init=False, default=None)

    def __post_init__(self):
        if not 0 < self.port < 65536:
            raise ValueError(f"port out of range: {self.port}")

    @classmethod
    def connect(cls, host, port=5432, timeout=5):
        self = cls(host, port)
        self.conn = socket.create_connection((host, port), timeout=timeout)
        return self

Client("db.internal") is now pure and instant; Client.connect("db.internal") is the one place a socket appears.

Alternatives and when to pick them.

ApproachSide effect visible at call siteUse when
__post_init__NoPure derivation and validation only
classmethod factoryYes (Client.connect)I/O, registration, resource acquisition
field(default_factory=...)No, but per-instanceMutable defaults, no external effect
custom __init__YesYou need to control assignment order; call __post_init__ yourself

Failure modes and detection. Invariants silently skipped after someone adds a custom __init__: detect with a test that constructs the invalid case and asserts it raises. Hidden I/O: assert Client(...) returns in microseconds, and grep __post_init__ bodies for anything that isn't pure. Leaked resources on replace: count open sockets across a replace call and assert the count is unchanged.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

What level of immutability does a frozen dataclass actually provide?

Answer

frozen=True buys shallow, per-instance immutability: the fields can't be rebound, but anything reachable through them can still change. It is not deep immutability, and it is not a security boundary.

What Python actually generates

For a frozen dataclass, @dataclass emits __setattr__ and __delattr__ that raise FrozenInstanceError: a subclass of AttributeError, so except AttributeError catches it. The generated __init__ doesn't go through that guard: it assigns each field with object.__setattr__(self, name, value), which is why construction still works. And because eq=True is the default, frozen=True also generates __hash__ over the tuple of fields with compare=True.

Python
from dataclasses import dataclass, FrozenInstanceError

@dataclass(frozen=True)
class Order:
    id: int
    items: list

o = Order(1, [])
o.id = 2                        # FrozenInstanceError
o.items.append("widget")        # fine — no __setattr__ involved
hash(o)                         # TypeError: unhashable type: 'list'
object.__setattr__(o, "id", 9)  # fine — bypasses the guard

Trace: o.id = 2 dispatches to the generated Order.__setattr__, which raises. o.items.append(...) is a method call on the list object; attribute lookup is untouched, so nothing stops it. hash(o) runs the generated __hash__, which hashes (self.id, self.items); hashing the list raises TypeError. object.__setattr__ skips the class's __setattr__ entirely.

So the level is: field rebinding blocked, contents not, hashability conditional on the field types.

Where it bites

The dangerous case is a mutable field whose class is hashable. Put such an object in a set, mutate it through a method, and the set's bucket is now stale: lookups miss and you get duplicates. list fails loudly at hash(); a custom mutable class with __hash__ fails silently. Detection: assert hash(o) succeeds at construction time, and keep only hashable field types (int, str, tuple, frozenset, Enum) in anything used as a key.

Two more: you cannot mix frozen and non-frozen dataclasses in one inheritance chain. @dataclass raises TypeError at class-creation time. And frozen says nothing about thread safety; two threads mutating the same list field race exactly as they would without it.

Alternatives and when to pick them

typing.NamedTuple is also shallow and hashable-if-contents-hashable, but it's a tuple, so it's lighter and unpackable. attrs with @define(frozen=True) is shallow too, but gives you on_setattr hooks and validators. Pydantic v2's ConfigDict(frozen=True) is shallow but validates on construction. None of them give deep immutability: for that, convert at construction (tuple(items), frozenset(tags)) and keep the frozen dataclass as the envelope.

Pick frozen when you want a value object with stable identity and cheap equality, and you control the field types. Don't pick it as a substitute for defensive copying or as a concurrency guarantee.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

Explain the semantic difference between replacement and raw cloning.

Answer

Core answer. dataclasses.replace(obj, **changes) is a reconstruction: it builds a new instance by calling obj.__class__.__init__ with the current value of every init=True field, overridden by changes. Raw cloning (copy.copy, copy.deepcopy, or obj.__dict__.copy()) is a state copy: it allocates a new object and copies the attribute dictionary without running __init__ or __post_init__. Three consequences decide which you want:

  1. init=False fields. replace skips them: they are never passed to __init__ and are recomputed by __post_init__. Raw cloning copies them verbatim.
  2. InitVar pseudo-fields. They are not in fields(), so replace never carries them over; if the class requires one without a default, replace raises TypeError. Raw cloning never needs them.
  3. Side effects and validation in __init__/__post_init__ run again under replace, and do not under raw cloning.

Worked trace (Python 3.10+; replace semantics unchanged since 3.7):

Python
from dataclasses import dataclass, field, replace, InitVar
import copy

@dataclass
class Order:
    items: list[float]
    tax_rate: InitVar[float] = 0.2
    total: float = field(init=False)

    def __post_init__(self, tax_rate: float) -> None:
        self.total = round(sum(self.items) * (1 + tax_rate), 2)

o = Order([10.0, 20.0])
print(o.total)                          # 36.0

r = replace(o, items=[10.0, 20.0, 30.0])
print(r.total)                          # 72.0

c = copy.copy(o)
c.items.append(30.0)
print(c.total, r.total)                 # 36.0 72.0

Step by step:

  • Order([10.0, 20.0]) calls __init__(items=[10.0, 20.0], tax_rate=0.2); __post_init__ sets total = round(30.0 * 1.2, 2) = 36.0.
  • replace(o, items=[10.0, 20.0, 30.0]): fields(o) yields items (init=True) and total (init=False). items is in changes; total is skipped. tax_rate is an InitVar, absent from fields(), so it is not added and the default 0.2 applies. The call is Order(items=[10.0, 20.0, 30.0]) → total = round(60.0 * 1.2, 2) = 72.0.
  • copy.copy(o) allocates a new object via __reduce_ex__ and copies __dict__; total is 36.0 and __post_init__ never runs. c.items is the same list as o.items, so the append is visible through both; c.total stays 36.0 while the true sum is now 60.0.

Failure modes and detection.

  • replace(o, total=99.0) → ValueError: field total is declared with init=False, it cannot be specified with replace(). You cannot override a derived field through replace; you must change an input it derives from.
  • Drop the default (tax_rate: InitVar[float]) and replace(o, items=[...]) raises TypeError: Order.__init__() missing 1 required positional argument: 'tax_rate'. Every required InitVar must be re-supplied on each replace call.
  • A stale derived field is an invariant violation: total != round(sum(items) * (1 + tax_rate), 2). Assert that in tests, or make total a @property/cached_property so it cannot go stale at all.
  • obj.__dict__.copy() fails on @dataclass(slots=True) (3.10+): there is no __dict__. copy.copy handles slots through __reduce_ex__, and it also works on frozen dataclasses, because state is restored into the dict rather than through __setattr__. Frozen-ness is not a reason to prefer replace.

Choosing. Use replace when the object is a value whose invariants are enforced at construction, when you want __post_init__ validation to re-run, and when you are producing a modified copy (the wither pattern). The cost is that construction runs again, so any side effect in __post_init__ (logging, registry insertion, a counter, a DB write) fires a second time. Use copy.copy/deepcopy when you want a snapshot of current state including derived fields, when construction is expensive or has side effects, or when the class has required InitVars you do not want to re-supply; accept that derived fields can go stale and invariants are not re-checked. Reach for deepcopy when fields are nested mutables and you need independence: both replace and copy.copy are shallow, as the trace shows.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Evaluate slots for memory, inheritance, serialization, and tooling compatibility.

Answer

Core answer (first 90 seconds)

@dataclass(slots=True) (Python 3.10+) generates __slots__ from the fields and returns a new class object. Each instance then stores fields at fixed offsets in the object instead of in a per-instance __dict__. Reach for it when you allocate many long-lived instances of a class whose field set is fixed and whose MRO is fully slotted. Skip it when instances need ad-hoc attributes, weak references, cached_property, or when a non-slotted base class already hands them a __dict__.

Mechanism

Without slots, obj.x resolves through type(obj).__dict__['x'].__get__(obj) and then a lookup in obj.__dict__. With slots, the class gets a member descriptor per field that reads and writes a fixed byte offset (tp_members), so the dict is never consulted. That is why it is both smaller and faster, and why an undeclared attribute raises AttributeError instead of quietly landing in a dict.

Memory arithmetic (CPython 3.11, x86-64, sys.getsizeof)

componentbytes
object + GC header32
__dict__ pointer8
__weakref__ pointer8
empty dict64
dict with 1-5 entries184
each slot8

A 3-field dataclass: no slots = 32 + 8 + 8 + 184 = 232 B; slots=True = 32 + 3x8 = 56 B. About 4x per instance, so 10M instances save roughly 1.8 GB.

Inheritance

Slots only remove __dict__ if every class in the MRO is slotted. A non-slotted base, or a subclass that omits slots=True, reintroduces __dict__ and the win disappears. slots=True also recreates the class, so zero-argument super() breaks:

Python
from dataclasses import dataclass

@dataclass(slots=True)
class Base:
    x: int

@dataclass(slots=True)
class Child(Base):
    y: int
    def total(self):
        return super().x + self.y
        # TypeError: super(type, obj): obj must be an instance or subtype of type

Fix: call super(Child, self) explicitly, or drop slots=True on the child. The same class replacement means any decorator or registry that captured the pre-decoration class now holds a stale object.

Serialization

Default pickle works: protocol >= 2 has always handled slots through __reduce_ex__, and 3.11 added object.__getstate__ so even protocol 0/1 works. On 3.10 and earlier, protocol 0/1 raises TypeError: ... a class that defines __slots__ without defining __getstate__ cannot be pickled. The failure you actually hit is a custom __getstate__ that returns a dict for a slots class: unpickling calls object.__setstate__, which does self.__dict__.update(state) and raises AttributeError because there is no __dict__. Pair any custom __getstate__ with a matching __setstate__.

Tooling compatibility

featurewith slots=True
weakref.ref(obj)TypeError: cannot create weak reference to 'X' object unless __weakref__ is in the slots
functools.cached_propertyTypeError: No '__dict__' attribute on 'X' instance to cache 'y' property.
vars(obj)TypeError
obj.new_attr = 1AttributeError
copy.deepcopyworks, same protocol as pickle
mypy / pyrightunderstand slots

Failure modes and detection

  • Silent memory regression from a non-slotted base: assert not hasattr(obj, '__dict__') in a test, or check sys.getsizeof on a sample.
  • super() breakage fires at call time, not import: cover it with a test that calls every method.
  • Weakref and cached_property fail on first use: add a smoke test that constructs and exercises the object.
  • Third-party code that sets attributes on your instances now raises AttributeError; grep for setattr against the type.

When not to use

Skip slots=True if instances are few, if the class is a base others subclass with extra attributes, if you rely on __dict__-based tooling (some ORMs and serializers introspect it), or if you need weakrefs without adding __weakref__ to the slots.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How would you evolve a dataclass without breaking positional class patterns?

Answer

Positional class patterns like case Point(x, y): read Point.__match_args__, a tuple @dataclass generates from the field names in definition order, excluding keyword-only fields and fields with init=False. To evolve without breaking those patterns, append new fields at the end, give them defaults, and mark them kw_only=True if they should stay out of the pattern surface. Never reorder, rename, or remove an existing field, and never flip an existing field to keyword-only: each of those changes the tuple and silently rebinds or rejects existing patterns.

Mechanism

Python
from dataclasses import dataclass, field

@dataclass
class Point:
    x: int
    y: int

print(Point.__match_args__)  # ('x', 'y')

Appending a defaulted field extends the tuple; old patterns still match because they consume a prefix:

Python
@dataclass
class Point:
    x: int
    y: int
    z: int = 0
    label: str = field(kw_only=True, default='')

print(Point.__match_args__)  # ('x', 'y', 'z')

label is keyword-only, so it never enters __match_args__. z is positional and defaulted, so Point(1, 2) still works and case Point(x, y) still binds the first two fields.

Reordering is the break:

Python
@dataclass
class Point:
    y: int
    x: int

print(Point.__match_args__)  # ('y', 'x')

Now case Point(x, 0) binds x to the first field, which is y. The pattern compiles and runs; it just binds the wrong value. That is the failure mode to test for.

Worked trace

Python
def describe(p):
    match p:
        case Point(0, 0):
            return 'origin'
        case Point(x, 0):
            return f'on x-axis at {x}'
        case Point(0, y):
            return f'on y-axis at {y}'
        case Point(x, y):
            return f'at ({x}, {y})'

print(describe(Point(3, 0)))  # on x-axis at 3

After appending z: int = 0, describe(Point(3, 0)) still prints on x-axis at 3 because the pattern only uses two positional sub-patterns. After reordering to y, x, Point(3, 0) constructs y=3, x=0, and describe prints on x-axis at 3, but the point is actually on the y-axis. The test that catches this constructs a known instance and asserts the bound values, not just the return string.

Trade-offs

  • Appending with defaults is the cheapest safe change. It still changes __init__, __repr__, and, if eq=True (the default), equality. Two instances that compared equal before may now differ. Test equality separately.
  • Making new fields keyword-only keeps __match_args__ unchanged, but callers cannot pass them positionally. That is usually fine for new fields and is the strongest guarantee.
  • Pinning __match_args__ explicitly (or passing match_args=False and defining it yourself) freezes the pattern surface, but if you also reorder fields, positional construction and pattern matching use different orders. That is a footgun; only pin if you also keep construction order stable.
  • match_args=False removes positional patterns entirely unless you define __match_args__ yourself. Use it only if you are prepared to own the tuple.

Failure modes and detection

  • Silent field swap from reordering: pattern binds wrong values. Detect with a test that matches a known instance and asserts each bound name.
  • Keyword-only flip on an existing field: case Point(x, y, z) raises TypeError: Point() accepts 2 positional sub-patterns (3 given). Detect with a pattern test.
  • Removing a field: same TypeError, plus broken positional construction. Detect with construction and pattern tests.
  • Adding a field without a default: breaks positional construction that omits it. Detect with construction tests.
  • Adding a field with eq=True: changes equality. Detect with equality tests.

__match_args__ generation and kw_only were added in Python 3.10. The rules above apply to 3.10+.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Compare structural Protocols with behavioral runtime contracts.

Answer

Core answer. "Structural Protocol" means typing.Protocol (PEP 544, Python 3.8+): a class satisfies the interface by having the right members, with no inheritance, and the check runs in the type checker (mypy/pyright), not at runtime. "Behavioral runtime contract" means an interface enforced when the object is used: abc.ABC + @abstractmethod (nominal, enforced at instantiation) or zope.interface's verifyObject (checks member presence and call signature at runtime). The decision: use a Protocol when you must accept objects you don't own; use an ABC when you own the hierarchy and want to force implementation; reach for verifyObject or inspect.signature only when you must reject a plugin at load time.

Why the runtime check is shallow. @runtime_checkable makes isinstance() work, but CPython's _ProtocolMeta.__instancecheck__ only collects the protocol's member names and checks each is present on the instance. It never calls inspect.signature, never reads annotations, never runs the body. Python 3.12 changed the lookup to inspect.getattr_static(), so non-method members count and descriptors aren't invoked, but the check is still presence-only.

Python
# Python 3.12
from typing import Protocol, runtime_checkable

@runtime_checkable
class Sender(Protocol):
    def send(self, payload: bytes) -> int: ...

class Fake:
    def send(self, payload):      # one arg, no annotations
        return "ok"               # returns str, not int

print(isinstance(Fake(), Sender))

Trace: isinstance(Fake(), Sender) collects Sender's members (send), finds send on the instance, returns True. The -> int annotation is never read. Output: True.

What the alternatives actually enforce.

Python
from abc import ABC, abstractmethod

class SenderABC(ABC):
    @abstractmethod
    def send(self, payload: bytes) -> int: ...

class Fake2(SenderABC):
    def send(self, payload):
        return "ok"

Fake2()   # instantiates fine

Trace: Fake2 overrides send, so __abstractmethods__ is empty and Fake2() succeeds. The ABC forced inheritance, not the signature.

Python
from zope.interface import Interface, implementer
from zope.interface.verify import verifyObject

class ISender(Interface):
    def send(payload: bytes) -> int: ...

@implementer(ISender)
class Fake3:
    def send(self, payload):
        return "ok"

verifyObject(ISender, Fake3())

Trace: verifyObject finds send present, then compares signatures. Both take (payload), so it passes. Add a required parameter (def send(self, payload, timeout)) and it raises zope.interface.exceptions.BrokenMethodImplementation. Return type is still not checked.

typing.Protocolabc.ABCzope.interface
satisfied byshape, at type-check timeexplicit inheritance@implementer / __conform__
runtime checkisinstance via @runtime_checkable: member presenceisinstance: MRO onlyverifyObject: presence + signature
signature checkednonoyes (arity/names)
semantics/invariantsnonoonly if you write validateInvariants
costzero at runtimezero at runtimeverifyObject walks methods; run once at startup

Failure modes. isinstance(Fake(), Sender) returns True, then Fake().send(b"x") returns "ok" and the consumer breaks on len(): the error surfaces far from the check. issubclass(Fake, Sender) raises TypeError when the protocol has non-method members. Before 3.12, isinstance ignored data members entirely, so a class missing a required attribute passed. @abstractmethod only blocks instantiation of the class that declares it; a subclass can override with any signature.

Decision point. Third-party objects you can't modify → Protocol, and let the type checker enforce shape. A hierarchy you own → ABC, so a missing method fails at construction. A plugin loaded from config where a wrong signature must fail before traffic → verifyObject, or inspect.signature against a stored reference. None of the three checks semantics; that stays in tests.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Compare ABCs and Protocols for a library extension point.

Answer

Assume Python 3.8+ (code below checked on 3.12), you ship the library, and third parties write plugins you don't control. Default to publishing a Protocol for the interface; add an ABC only when you also need to hand plugins shared code or to reject a broken plugin at construction time.

Protocol is structural: a plugin satisfies it by having the right methods, with no import of your package and no base class. ABC is nominal: membership comes from subclassing or register(), and ABCMeta refuses to instantiate a class with unresolved abstract methods. Both can be checked at runtime, but only the ABC's check is cheap and cached: ABCMeta stores positive results in _abc_cache and negatives in _abc_negative_cache, while a @runtime_checkable protocol re-walks its members with hasattr on every isinstance call.

Python
# Python 3.12
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable

class Serializer(ABC):
    @abstractmethod
    def dumps(self, obj: object) -> bytes: ...

    def dumps_many(self, objs: list[object]) -> bytes:   # shared code
        return b"".join(self.dumps(o) for o in objs)

class JsonSerializer(Serializer):
    def dumps(self, obj: object) -> bytes:
        return b"{}"

@runtime_checkable
class SerializerProto(Protocol):
    def dumps(self, obj: object) -> bytes: ...

class CsvSerializer:                 # never imports the library
    def dumps(self, obj: object) -> bytes:
        return b"a,b"

class Broken:
    dumps = 5                        # attribute exists, not callable

Trace, in order:

expressionresult
Serializer()TypeError naming the abstract method dumps
JsonSerializer().dumps_many([1, 2])b"{}{}"
Serializer.register(CsvSerializer) then isinstance(CsvSerializer(), Serializer)True
CsvSerializer().dumps_many([1])AttributeError: 'CsvSerializer' object has no attribute 'dumps_many'
Serializer in CsvSerializer.__mro__False
isinstance(CsvSerializer(), SerializerProto)True
isinstance(Broken(), SerializerProto)True: presence only
Broken().dumps(1)TypeError: 'int' object is not callable
dimensionABCProtocol
membershipsubclass or register()any class with matching members
enforcementTypeError at constructionnothing until the method is called
shared codeconcrete methods inheriteddefault bodies only for explicit subclasses
isinstance costcached lookup after first callhasattr per member, every call
plugin dependencymust import your packagenone
static checkingmypy/pyright nominalmypy/pyright structural

Failure modes worth testing for. A runtime_checkable protocol checks attribute presence, not signature or callability: Broken above passes isinstance and fails at the call site, deep inside your library. Catch it with a conformance test that calls every protocol method on a stub plugin, plus mypy or pyright in CI. issubclass against a runtime_checkable protocol that has a non-method member raises TypeError, so keep data attributes out of any protocol you intend to issubclass-check. register() makes isinstance return True without injecting methods or touching the MRO, so a registered class that skips a concrete method blows up on first use. And a protocol class itself cannot be instantiated (TypeError: Protocols cannot be instantiated), so it can never double as a default implementation.

When not to use a protocol: if the extension point must guarantee that a plugin set required state before any method runs, or if you want to ship a working base implementation, an ABC does that and a protocol cannot. If you need neither, a protocol without @runtime_checkable costs nothing at runtime and keeps plugins free of your package.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Explain how `__init_subclass__` and `__set_name__` work, and when they beat writing a metaclass.

Answer

Both hooks let a base class act on subclasses without a metaclass, but they fire at different moments of class creation and see different things.

__init_subclass__ is an implicit classmethod on the base. When class Child(Base) executes, type.__new__ builds the class object and then calls Base.__init_subclass__(cls=Child, **kwargs_from_class_header). It never runs for Base itself, and it runs once per subclass, including subclasses of subclasses. Keyword arguments in the class header are forwarded: class JsonPlugin(Plugin, key="json") calls Plugin.__init_subclass__(key="json").

__set_name__ is a descriptor hook. During the same type.__new__, every object in the new class's namespace that defines __set_name__ gets obj.__set_name__(owner=Child, name="x"). Only the new namespace is scanned, a descriptor inherited from a base keeps the name it was given there, and it is not re-run if you later setattr a descriptor onto the class.

Ordering is fixed and documented: __set_name__ calls happen first, then __init_subclass__. So a base's __init_subclass__ can already read field names that descriptors recorded.

python class Base: def init_subclass(cls, **kwargs): super().init_subclass(**kwargs) print("init_subclass", cls.name)

class Desc: def set_name(self, owner, name): print("set_name", owner.name, name)

class Child(Base): x = Desc()

set_name Child x init_subclass Child

Practical use: a plugin registry:

python class Plugin: registry: dict[str, type["Plugin"]] = {}

def __init_subclass__(cls, *, key: str | None = None, **kwargs):
    super().__init_subclass__(**kwargs)
    name = key or cls.__name__.lower()
    if name in Plugin.registry:
        raise ValueError(f"duplicate plugin key {name!r}")
    Plugin.registry[name] = cls

class JsonPlugin(Plugin, key="json"): ...

The duplicate-key check runs at import time, so a collision surfaces as an ImportError rather than a runtime surprise. Note that __init_subclass__ fires before class decorators are applied, so a decorator that sets cls.key is too late.

A descriptor that records its own field name:

python class Field: def set_name(self, owner, name): self.name = name self.storage = "_" + name

def __get__(self, obj, objtype=None):
    if obj is None:
        return self
    return getattr(obj, self.storage)

def __set__(self, obj, value):
    setattr(obj, self.storage, value)

The stdlib dataclasses module does this by hand: _process_class calls f.__set_name__(cls, f.name) on each Field, because the class object already exists by the time the fields are built.

Reach for a metaclass instead only when you must change the class object itself (its __bases__, its __slots__ layout, class-level __getattr__) or intercept classes that don't share your base. A metaclass runs for the class it is attached to and every subclass, and only one can win: class C(A, B) with unrelated metaclasses raises TypeError: metaclass conflict. __init_subclass__ composes through the MRO instead; each base contributes its own hook, chained by cooperative super().__init_subclass__(**kwargs).

Failure modes. Omitting super().__init_subclass__(**kwargs) silently skips sibling bases' hooks under multiple inheritance: the symptom is a registry missing entries for classes that look correct. A descriptor assigned after class creation never gets __set_name__, so self.name is unset and the first attribute access raises AttributeError. An exception inside either hook propagates out of the class statement, so the class is never bound: good for validation, fatal if one plugin module has a typo.

Curated: · Written: · Reviewed:

Difficulty: Hard