Skip to the page

Classes and typing · senior

Properties, descriptors and metaclasses

A property runs code on get, set or delete while callers still write obj.x. Underneath it is a descriptor, and the same idea powers methods, ORMs and Pydantic. Metaclasses are the class of a class and are rarely needed in application code.

The notes

What you must know

  • A property runs code on get, set or delete. Python style: start with public attributes and add a property later; do not write getters and setters for every field.
  • A property is a descriptor: an object on the class with get and set. A data descriptor (it has set) wins over the instance dict; the instance dict wins over a non-data descriptor.
  • Functions are non-data descriptors, which is how obj.method becomes bound to obj.
  • cached_property computes once and stores the result in the instance dict, so it needs a dict and does not work with slots.
  • Keep properties cheap. A property that does network calls surprises callers.
  • Classes are objects too. Their type is a metaclass, type by default. A metaclass runs when the class statement runs.
  • Libraries use metaclasses: ABCMeta, Enum, ORMs, Pydantic. In application code prefer init_subclass (PEP 487), class decorators and set_name.
  • A class whose bases have unrelated metaclasses fails with a metaclass conflict.

The red pen

Common traps: mistake → fix

  • Mistake: Write getters and setters for every field like Java

    Fix: use plain attributes and add a property when needed.

  • Mistake: A property is a cheap attribute

    Fix: it may hide slow work.

  • Mistake: Use a metaclass to register subclasses

    Fix: init_subclass or a decorator is simpler.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does @property do and when would you use it?
  2. How does a property work underneath?
  3. Why does obj.method become a bound method?
  4. What is a metaclass? Have you ever needed one?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview