๐Ÿ Design Patterns with Python
Home Chapters Examples Diagrams Bibliography GitHub โ†—
  1. Home
  2. Idiomatic Python
Part 9 5 chapters

Idiomatic Python

Decorators done right, descriptors and properties, singledispatch, metaclasses and __init_subclass__, and dynamic attributes with __getattr__.

Chapter 26

Decorators done right

The @ syntax is given, but getting a decorator right isn't: what wraps copies, what ParamSpec keeps for mypy, bare use of a factory, stacking order and class decorators.

Read โ†’
Chapter 27

Descriptors and properties

One validator, written once, guarding every field that needs it, and when a plain property or a cached one is the better tool.

Read โ†’
Chapter 28

singledispatch: the Visitor the language gives you

Dispatch on the type of the first argument without a visitor class, and the choices that matter once registrations can live in other modules.

Read โ†’
Chapter 29

Metaclasses, __init_subclass__, and registries

Register subclasses by a class keyword, refuse a bad class when it is defined, and see what only a metaclass can still do.

Read โ†’
Chapter 30

Dynamic attributes: __getattr__ and Proxy as a feature

An object that loads its own fields on first access, and how to keep __getattr__ out of recursion and consistent with dir, copy and mypy.

Read โ†’
โ† Previous part Coordinating and Traversing Next part โ†’ Patterns in the Wild
Design Patterns with Python
Prose, diagrams and decks: CC BY 4.0. Sample code: Apache 2.0.
Source on GitHub โ†—  ยท  File an issue โ†—