Unit 3 of 9 · about 5 hours · explain, implement

Attribute lookup, object protocols and dataclasses

Config and record objects cross every boundary in later stages. Lookup, equality and default rules decide what breaks silently.

You'll be able to

  • Trace attribute lookup through data descriptors, the instance dictionary, non-data descriptors and the MRO without running code.
  • Implement a class with deliberate dunders and state the equality and hashing consequences.
  • Build a validated frozen dataclass with safe defaults, serialization and malformed-input tests.

Covers

Attribute lookup, class and instance state, and method bindingCore object protocols and deliberate dunder methodsDataclasses, default factories, equality, ordering and frozen state
1

Read

In this order, only the parts listed

0 of 7 done

  1. Special methodsStas' Python Cookbook - selected path

    Classes and Objects: Dunder (special) methods with the Vector example; __repr__ for developers and __str__ for users

  2. Attribute access and delegationStas' Python Cookbook - selected path

    Classes and Objects: Dynamic attributes and delegation; __getattr__ runs only after normal lookup fails

    Skip the Null-object/Dummy classes subsection. A catch-all __getattr__ hides typos and works against this unit's explicitness goal.

  3. Special method lookup and attribute accessPython language reference

    Section 3.3.13 Special method lookup (implicit calls bypass the instance) and 3.3.2 Customizing attribute access (__getattribute__ versus __getattr__)

  4. The @dataclass decorator and fieldsdataclasses - data classes

    The @dataclass parameters (eq, order, frozen, slots), field() with default_factory, Frozen instances and Post-init processing

  5. Dataclass helpersdataclasses - data classes

    asdict, astuple and replace for serialization and copy-with-change

  6. Dunder MethodsAlgoMaster Python - structured revision

    The Dunder Methods lesson and its exercise for recall

  7. Data ClassesAlgoMaster Python - structured revision

    The Data Classes lesson and Exercise: Data Classes after the cookbook pass

2

Focus on

  • Lookup order is data descriptors, then the instance dictionary, then non-data descriptors and class attributes. Implicit dunder calls use the type only, so an instance __len__ attribute never changes len(obj).
  • object.__eq__ is identity by default. Defining __eq__ without __hash__ sets __hash__ to None and the instances become unhashable.
  • Dataclass mutable defaults raise ValueError at class creation; field(default_factory=list) gives each instance its own list.
  • The cookbook writes Config(frozen=True). That call is wrong and raises TypeError; frozen belongs on the decorator as @dataclass(frozen=True).
Common mistakes · 3
  • Setting an instance __len__ to change len(). Implicit lookup skips the instance dictionary.
  • Expecting < on a default dataclass to work. order defaults to False, so P(1) < P(2) raises TypeError.
  • Sharing state through a plain list default. The decorator rejects it with ValueError; read that error as protection.
3

Try it yourself

Closed-book, before checking anything

Closed-book, write a frozen slotted dataclass with two validated fields, __post_init__ checks, an asdict round trip and a replace() change. State why its instances are hashable and which line breaks if frozen is removed.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.A data descriptor, an instance entry and a plain class attribute all define x. Which does obj.x return?Answer

    The data descriptor wins. Instance lookup only beats non-data descriptors and plain class attributes.

  2. 2.A class defines __eq__ but no __hash__. What does hash(instance) do?Answer

    It raises TypeError. Defining __eq__ sets __hash__ to None unless __hash__ is also defined.

  3. 3.What happens at class creation for tags: list = [] inside @dataclass, and what is the fix?Answer

    ValueError: mutable default is not allowed. Use tags: list = field(default_factory=list).

  4. 4.Why does removing frozen=True from a hashed dataclass break set membership?Answer

    Instances become unhashable because eq without frozen sets __hash__ to None. Mutable hashed instances are worse: edits strand them in the wrong bucket.

5

Practice

  • AlgoMaster Python: Exercise: Data Classes

    Exercises 1 to 5, especially Exercise 2: Compare Products by Field Values and Exercise 4: Give Each Cart Its Own Item List

    Use for recall; the frozen dataclass in Reproduce is the implement-depth check.

You're done when

Your frozen dataclass validates, serializes and round-trips, and you can trace a lookup and an equality case without running code.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 4 more in the section
  • Stas' Python Cookbook - selected pathStas Bekman · primary

    Run Part I on dictionaries, iteration, functions, closures, decorators, classes and context managers; Part II on modules, files, paths, environment and arguments; and Part IV on versions, dependencies, packaging and code quality. Finish by building one src-layout package from a blank directory.

  • Python language referencePython Software Foundation · required

    Check Data model, Execution model, Import system and Exceptions whenever a claim depends on Python semantics. These pages are the authority when the course and a runtime observation disagree.

  • AlgoMaster Python - structured revisionAlgoMaster · support

    Use Functions, Modules and Packages, OOP, Advanced OOP, Exception Handling, Iterators and Generators, Type Hints and Annotations only after the cookbook pass. Open it for recall practice or a diagnosed weak mechanism, not as a second complete course.

  • dataclasses - data classesPython Software Foundation · reference

    Read the @dataclass parameters (eq, order, frozen, slots), field() with default_factory, frozen instances, post-init processing, replace, asdict and astuple. Use for the validated frozen dataclass in attributes-protocols-dataclasses.

Also in this section

  • Packaging Python ProjectsPython Packaging Authority · required

    Follow the packaging tutorial once from a blank directory, using a src layout, pyproject.toml, an isolated build and a clean-environment installation test.

  • typing - type hints and protocolsPython Software Foundation · reference

    Read Protocols for structural typing and runtime_checkable limits, Generics for TypeVar generics, and assert_type for narrowing checks. Use for the Protocol and narrowing parts of type-hints-protocols; PEP 695 syntax itself is in the language reference.

  • gc - cycle garbage collectorPython Software Foundation · reference

    Read the cycle collector interface: collect, get_count, garbage and disable/enable. Use for the cycle-collection and measurement parts of refcounting-gc-weakrefs.

  • weakref - weak referencesPython Software Foundation · reference

    Read weak-reference objects (ref callbacks, proxy objects) and the WeakValueDictionary example. Use for the weak-reference part of refcounting-gc-weakrefs.