Skip to the page

Classes and typing · core

Dunder methods, dataclasses, Pydantic and slots

Dunder methods are the hooks Python calls for you. Defining eq removes hash unless you define it again. Dataclasses, Pydantic models and attrs each fit a different place, and slots saves memory at a cost.

The notes

What you must know

  • repr is unambiguous, for logs and debugging; str is for people. Also eq, lt (with functools.total_ordering), hash, add and radd, bool, len, iter, getitem, contains.
  • Defining eq sets hash to None, so the class becomes unhashable until you define hash from the same immutable fields. Equal objects must have equal hashes.
  • Return NotImplemented (not False) for unknown types so Python can try the other side. sum() starts from 0, so Money needs radd that handles 0, or sum(items, Money(0)).
  • A dataclass gives init, repr and eq and supports frozen, slots and kw_only. Type hints are not checked at runtime. Use field(default_factory=...) for mutable defaults.
  • Pydantic v2 validates and converts at runtime, reads and writes JSON and makes JSON Schema. Lax mode turns "499.00" into a number; strict mode refuses it. It costs more per object than a dataclass.
  • Rule of thumb: validate at the edges (API input, config, model output) and use plain dataclasses inside. attrs is the third-party library that dataclasses grew from. TypedDict is for typed dicts; NamedTuple for small read-only records.
  • frozen=True stops reassigning fields, but a list field can still be changed in place. Money is Decimal plus a currency.
  • slots replaces the per-object dict: less memory, slightly faster access, and a typo like obj.nmae = 1 raises AttributeError. You lose new attributes, cached_property and weak references. Every class in the chain needs slots. Measure with tracemalloc, because sys.getsizeof is shallow.

The red pen

Common traps: mistake → fix

  • Mistake: Dataclasses validate types

    Fix: they do not; only Pydantic validates at runtime.

  • Mistake: hash can return id(self) while eq compares values

    Fix: equal objects would have different hashes and break dicts and sets.

  • Mistake: Add slots everywhere for speed

    Fix: only for millions of small objects, after measuring.

  • Mistake: Use Pydantic models for every internal object in a hot loop

    Fix: validation has a cost.

Easy to hard

Questions interviewers ask, easy to hard

  1. What are dunder methods? Which ones would a Money class need?
  2. Why does a class with eq stop working as a dict key?
  3. Dataclass, Pydantic model, attrs or plain class for an order from a partner API?
  4. What does slots do and what do you lose?
  5. Why does sum([Money(1), Money(2)]) fail?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview