typestar

Pythonic Python

53 steps in 14 sets of Python.

The difference between Python that works and Python that reads like Python. Comprehensions first, then decorators and the closures underneath them, generators and the itertools that pair with them, and the dunder protocols that let your own objects behave like built-in ones.

After that it gets less polite. Descriptors, __init_subclass__ and metaclass-adjacent machinery, functools and operator, typing beyond the basics, and async twice over, once for the syntax and once for the patterns that actually come up. Not all of this is code you should write. All of it is code you will read.

Start this tour

Comprehensions

Decorators & closures

Generators & itertools

Protocols & context managers

Typing & dataclasses

Async

Threads & processes

Attributes & descriptors

  • __slots__Declaring the attributes up front drops the per-instance dict.
  • Properties with validationA property turns attribute access into a method call, so invariants hold.
  • DescriptorsThe protocol properties are built on: __get__ and __set__ on a class attribute.

Class machinery

  • Abstract base classesABCs state the interface and refuse to instantiate until it is met.
  • __init_subclass__A hook that runs when a subclass is defined — a registry without a metaclass.
  • A metaclassThe class of a class: it runs at definition time and can rewrite the class.

functools & operator

  • functoolspartial, reduce and cached_property: three tools worth reaching for.
  • singledispatchOne function name, an implementation chosen by the first argument's type.
  • The operator moduleNamed functions for the operators, which beats a lambda in a sort key.

Typing in depth

  • TypeVar and GenericA type parameter lets one class or function keep its caller's type.
  • ProtocolsStructural typing: anything with the right methods satisfies the protocol.
  • TypedDict and NewTypeTyping the shape of a dict, and giving a primitive a distinct name.
  • overloadSeveral signatures for one function, so the checker knows what comes back.

Data & enums

Async in depth

Encore

The other Python tours