7 routes42 sections324 units

Unit 3.3 · about 5 h

12 / 324

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.

  • explain
  • implement

You can now

  • 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 binding
  • Core object protocols and deliberate dunder methods
  • Dataclasses, default factories, equality, ordering and frozen state

Study, in this order

7 steps

  1. Special methods
    Stas' 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 delegation
    Stas' Python Cookbook - selected path

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

    Depth · 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 access
    Python 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 fields
    dataclasses - data classes

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

  5. Dataclass helpers
    dataclasses - data classes

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

  6. Dunder Methods
    AlgoMaster Python - structured revision

    The Dunder Methods lesson and its exercise for recall

  7. Data Classes
    AlgoMaster Python - structured revision

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

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).

Reproduce closed-book

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.

Traps

  • 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.

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.

Self-test

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

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

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

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

Completion criterion

Stop when

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

Mark passed, then open 3.4 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • Stas' Python Cookbook - selected path
    Stas Bekmanprimarycourse
    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 reference
    Python Software Foundationrequiredreference
    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 revision
    AlgoMastersupportpractice
    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 classes
    Python Software Foundationreferencereference
    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 Projects
    Python Packaging Authorityrequiredimplementation
    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 protocols
    Python Software Foundationreferencereference
    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 collector
    Python Software Foundationreferencereference
    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 references
    Python Software Foundationreferencereference
    Read weak-reference objects (ref callbacks, proxy objects) and the WeakValueDictionary example. Use for the weak-reference part of refcounting-gc-weakrefs.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels