Fluent Python

Data Structures

The Python Data Model

  • Using special methods
    • Users don’t have to memorize arbitrary method names.
    • Benefit from rich python std lib and avoid reinventing the wheel.
    • Special methods are meant to be called by the Python interpreter, not by you.
    • Dunder method = double-underscored method
    • Pythonic
  • # doctest: +ELLIPSIS directive to elide the output
  • __repr__
    • Called by interactive console and debugger
    • Similar to %r place holder and !r conversion field (for standard representation, without quote)
    • This method should be capable of recreating the object
  • __str__
    • Is meant for end users.
    • This falls back to __repr__
    • If only one is implemented, implement __repr__
  • __bool__
    • bool invokes __bool__ and uses the result
    • If not implemented, invoke __len__, if 0, return False
    • Otherwise truthy.
  • ABC
    • Sequence, Mapping, and Set
    • Collection should implement: Iterable, Sized, and Container
    • Since Python 3.7, dict is officially “ordered”, i.e. key insertion order is preserved
  • Reversed operator = when the special method on the first operand can’t be used
  • len() is not a method
    • When x is a built-in type, len(x) simply read from a field in the CPython C struct.
    • “Practicality is better than purity”
    • len may be considered as an unary operator
  • The Art of the Metaobject Protocol (AMOP)
    • metaobject = the objects that are the building blocks of the language itself
    • an API for core language constructs
    • A rich metaobject protocol enables extending a language to support new programming paradigms