Skip to content

Pythonic

This section closes the gap between "I know Python syntax" and "I can design code the Python way." Descriptors, decorators, context managers, and metaclasses make much more sense once you see them as layers on top of the data model and attribute lookup rules.

Quick takeaway: being Pythonic mostly means understanding the data model and then choosing the smallest tool that fits: descriptor, decorator, context manager, or metaclass. Most framework magic is really just this stack of hooks.

Questions This Part Answers

Why `len(obj)`?

Python syntax is connected to object protocol methods, not to arbitrary instance method names.

Why do fields feel magical?

Descriptors plus attribute lookup order explain ORM fields, computed attributes, and bound methods.

When is a dataclass enough?

Dataclasses are excellent for value objects, settings, and internal command payloads. They become painful when asked to own validation, persistence, and transport concerns at once.

Decorator or metaclass?

Both extend behavior, but they act at different times and with very different costs.

How do open-source projects stay Pythonic?

Read real snippets from Click, Requests, SQLAlchemy, Pydantic, and FastAPI to see how Pythonic design choices are encoded in production code.

How far should metaprogramming go?

Choose between `__init_subclass__`, `__set_name__`, class decorators, metaclasses, and import hooks with an explicit cost model.

How do you express scope?

Context managers are the clearest Pythonic way to express resource ownership and cleanup boundaries.

  1. Data Model
  2. Dataclasses
  3. Descriptors and Properties
  4. Open-source Pythonic Deep Dives
  5. Metaprogramming Advanced
  6. Decorators
  7. Context Managers
  8. Metaclasses

Practical Connections

  • FastAPI route decorators and dependency wiring
  • dataclass-based internal commands and value objects
  • Pydantic field annotations and field access behavior
  • SQLAlchemy instrumented attributes and class construction hooks
  • reading decorator/context manager/factory patterns in real open-source code
  • building a cost-aware tool-selection model for metaprogramming hooks

Built with VitePress for a Python 3.14 handbook.