πͺ Descriptors & Metaclasses
in Python
Understand Python descriptors and metaclasses: __get__, __set__, __set_name__, how property and classmethod work, validators, __init_subclass__, type() and when not to use metaclasses.
What this lesson is about
Every time you write @property, call a method, use @classmethod or define a field in a Django model or an SQLAlchemy table, Python quietly runs two pieces of machinery that most tutorials never show you. The first is the descriptor protocol: objects that live on a class and take over what happens when an attribute is read, written or deleted. The second is the metaclass: the object that builds a class in the first place. Together they explain why Python's object model feels so uniform, and why frameworks can offer such compact declarative syntax.
You will not need these tools every day, and I want to be honest about that up front. Most code is better served by plain classes, @property and dataclasses. But when you maintain a library, read framework internals, write a reusable validation layer or debug a puzzling AttributeError, knowing what happens underneath turns mystery into mechanism. I also want you to leave with good judgement, which includes knowing the simpler alternatives, __init_subclass__ and class decorators, that replace most metaclass use.
I have organised the page from the bottom up. We start with how attribute lookup works and write a first descriptor, then add __set__, __delete__ and __set_name__. After that we study data versus non-data descriptors, rebuild property, classmethod and staticmethod from scratch, and write reusable validators. Then we move to classes: __init_subclass__, type() as a class factory, metaclass __new__, __prepare__ and __call__, registries and plugins, and finally the cases where you should not reach for a metaclass. Every block runs with the standard library only, so press Run and experiment.
What you will learn
- βDescribe what the descriptor protocol is and where Python calls it
- βWrite descriptors using
__get__,__set__,__delete__and__set_name__ - βExplain why data descriptors beat instance attributes and non-data descriptors do not
- βRebuild
property,classmethodandstaticmethodto see how they really work - βBuild reusable validators that enforce types and ranges on attributes
- βHook into subclass creation with
__init_subclass__and class decorators - βCreate classes at runtime with
type()and customise creation with a metaclass - βDecide when a metaclass is justified and when a simpler tool is better
Why programmers should learn this
- β
Descriptors are the mechanism behind methods,
property,classmethod,staticmethod,functools.cached_propertyand__slots__, so understanding them explains behaviour you already use every day. - β Frameworks such as Django models, SQLAlchemy and Pydantic-style libraries rely on descriptors and class-creation hooks to give you declarative field definitions; reading their source becomes far easier.
- β A reusable validator descriptor lets you write a rule once and apply it to many attributes in many classes, instead of repeating the same property boilerplate.
- β
Knowing
__init_subclass__and class decorators lets you build plugin registries and class-level checks with a few lines, with no metaclass complexity. - β Judgement matters as much as knowledge: being able to say why a metaclass is the wrong tool is a sign of an experienced Python programmer and saves your teammates from clever, fragile code.
What attribute lookup really does
When you write obj.name, Python does not simply look in a dictionary. It runs a lookup procedure, implemented by object.__getattribute__, that checks several places in a precise order. Roughly: first it looks for name on the type of the object (and the classes it inherits from); if what it finds there is a descriptor, special rules apply; otherwise it checks the instance's own __dict__; and finally it falls back to a non-data descriptor or plain class attribute. If nothing is found, __getattr__ is tried, and then you get an AttributeError.
A descriptor is any object whose class defines at least one of __get__, __set__ or __delete__. When such an object is stored as a class attribute, Python calls those methods instead of just returning or replacing the object. That is the entire protocol. Nothing is registered and no base class is needed; having the method is enough, which is very Pythonic.
The signature of __get__ is __get__(self, obj, objtype=None). When you access the attribute through an instance, obj is that instance. When you access it through the class itself, obj is None, and by convention a descriptor then returns itself so tools such as help() and documentation generators can inspect it. The example below prints a line every time Python calls the descriptor, so you can watch the protocol working.
class Loud:
"""A descriptor that announces every lookup."""
def __get__(self, obj, objtype=None):
if obj is None:
print(" accessed through the class")
return self
print(" __get__ called for an instance")
return 42
class Box:
answer = Loud()
b = Box()
print("instance access:")
print(b.answer)
print("class access:")
print(type(Box.answer).__name__)instance access: __get__ called for an instance 42 class access: accessed through the class Loud
Line by line
- 1-9
Louddefines only__get__, which makes it a descriptor. Theobj is Nonebranch handles access through the class and returns the descriptor itself. - 8-9For instance access it prints a message and returns a fixed value, 42, instead of anything stored on the object.
- 12-13
answer = Loud()places the descriptor in the class body. It is a class attribute, which is where descriptors must live to work. - 16-18
b.answertriggersLoud.__get__(descriptor, b, Box)behind the scenes; you never call it yourself. - 19-20
Box.answerpassesobj=None, so we get the descriptor object back. I print only its type name because the default repr includes a memory address.
Descriptors only work when they are attributes of a class. If you assign a descriptor to an instance (b.x = Loud()), Python treats it as an ordinary value and never calls __get__.
__set__, __delete__ and __set_name__
A descriptor becomes much more useful when it also controls writing and deleting. __set__(self, obj, value) runs on obj.attr = value, and __delete__(self, obj) runs on del obj.attr. A descriptor that defines __set__ or __delete__ is called a data descriptor, and that distinction matters in the next section.
The key design question is: where does the descriptor store the value? The descriptor object is shared by every instance of the class, so it must never keep per-instance data on itself (self.value = ... would make all instances share one value, a classic bug). Instead, it stores data on the instance, usually in obj.__dict__ under a name derived from the attribute name.
How does the descriptor learn that name? Before Python 3.6 you had to pass it in by hand, writing age = Field('age'), which is repetitive and easy to get wrong. Now Python calls __set_name__(self, owner, name) on each descriptor when the class is created, passing the owning class and the attribute name. That small hook is what makes declarative fields pleasant. In the example I store values under a private-looking key, so the public name stays free for the descriptor itself.
class Field:
"""Stores its value on the instance under a private key."""
def __set_name__(self, owner, name):
self.public = name
self.private = "_" + name
print(f" __set_name__: {owner.__name__}.{name}")
def __get__(self, obj, objtype=None):
if obj is None:
return self
try:
return obj.__dict__[self.private]
except KeyError:
raise AttributeError(f"{self.public} has not been set") from None
def __set__(self, obj, value):
print(f" setting {self.public} = {value!r}")
obj.__dict__[self.private] = value
def __delete__(self, obj):
print(f" deleting {self.public}")
del obj.__dict__[self.private]
class User:
name = Field()
email = Field()
u = User()
u.name = "Glenn"
u.email = "glenn@example.com"
print(u.name, u.email)
print(sorted(u.__dict__))
del u.email
try:
print(u.email)
except AttributeError as exc:
print("AttributeError:", exc)
v = User()
v.name = "Ana"
print(u.name, v.name)__set_name__: User.name __set_name__: User.email setting name = 'Glenn' setting email = 'glenn@example.com' Glenn glenn@example.com ['_email', '_name'] deleting email AttributeError: email has not been set setting name = 'Ana' Glenn Ana
Line by line
- 4-7
__set_name__runs once per descriptor, during class creation, so the descriptor learns its own attribute name and builds a private key like_name. The print shows when it happens. - 9-16
__get__reads from the instance's__dict__. A missing key becomes a clearAttributeErrormentioning the public name. - 18-20
__set__is what makes this a data descriptor. It writes into the instance dictionary rather than onto the shared descriptor. - 22-24
__delete__removes the stored value, so a later read raises an error. - 27-29The class body creates two descriptors. The
__set_name__messages print as soon as the class statement finishes, before any instance exists. - 32-35Assignment goes through
__set__; the instance dictionary contains only_emailand_name, notnameoremail. - 36-40After
del u.email, reading it raisesAttributeErrorwith our message. - 42-44Two instances keep separate values because the data lives on each instance, not on the descriptor.
Notice that the class body printed the __set_name__ lines at definition time. That is an important mental model for everything that follows: class bodies run top to bottom when Python first reaches them, and hooks like this run during that process, not at the first instance.
Never write self.value = value inside __set__. The descriptor is shared by all instances, so every object would see the last value assigned.
Data versus non-data descriptors
Python decides who wins a lookup using a simple precedence rule. If the class attribute is a data descriptor (it defines __set__ or __delete__), it takes priority over the instance __dict__. If the instance dictionary has the name and the class attribute is only a non-data descriptor (just __get__), the instance dictionary wins. And a plain class attribute with no descriptor methods loses to the instance dictionary as well.
This rule is not trivia. It is the reason functions can be overridden on a single instance (functions are non-data descriptors), and the reason property cannot be overridden that way (property is a data descriptor, even if you never define a setter: it implements __set__ and raises AttributeError). It is also what makes caching work: a non-data descriptor can compute a value, store it in the instance dictionary, and from then on the instance entry shadows the descriptor so later reads are as fast as plain attribute access.
The experiment below puts one of each kind on a class and then forces an entry of the same name into the instance dictionary. Watch which value comes back.
class NonData:
def __get__(self, obj, objtype=None):
return "from the non-data descriptor"
class Data:
def __get__(self, obj, objtype=None):
return "from the data descriptor"
def __set__(self, obj, value):
raise AttributeError("read-only")
class Demo:
plain = "class attribute"
nd = NonData()
d = Data()
x = Demo()
for name in ("plain", "nd", "d"):
x.__dict__[name] = "instance dict"
print(f"{name:5} ->", getattr(x, name))
print("--- normal assignment ---")
try:
x.d = "new"
except AttributeError as exc:
print("blocked:", exc)
x.nd = "assigned"
print(x.nd)plain -> instance dict nd -> instance dict d -> from the data descriptor --- normal assignment --- blocked: read-only assigned
Line by line
- 1-3
NonDatadefines only__get__: a non-data descriptor, like a plain function. - 6-11
Dataadds__set__, which makes it a data descriptor. Here the setter refuses all writes. - 14-17Three class attributes of different kinds share the same instance.
- 21-23I write directly into
x.__dict__, bypassing normal assignment, so each name exists in both places. Then I read each withgetattr. - 22-23The plain attribute and the non-data descriptor are shadowed by the instance dictionary, but the data descriptor still wins and returns its own value.
- 26-29Normal assignment
x.d = ...goes through the data descriptor's__set__and is blocked. - 30-31Assigning to
x.ndhas no__set__to call, so Python simply stores the value in the instance dictionary.
A handy summary: data descriptor beats instance dict, instance dict beats non-data descriptor, non-data descriptor beats nothing. Remembering that order explains most descriptor surprises.
How property, classmethod and staticmethod work
Now you can see that nothing about @property is magical. It is a class written in C that implements __get__, __set__ and __delete__, and calls the functions you gave it. Writing it yourself in Python takes about fifteen lines and is the best way to remember the protocol.
Ordinary methods are descriptors too. A def inside a class creates a function object, and function objects define __get__. When you access obj.method, function.__get__(obj, type(obj)) runs and returns a bound method: a small object that remembers obj and inserts it as the first argument when called. That single mechanism is why self appears without you passing it. staticmethod is a descriptor whose __get__ returns the raw function with no binding, and classmethod returns a method bound to the class instead of the instance.
The code below rebuilds all three. I name them with a My prefix so they do not shadow the built-ins. After that I show the bound-method behaviour on a real function, and a tiny caching descriptor in the style of functools.cached_property, which is a non-data descriptor that replaces itself with the computed value.
import types
class MyProperty:
def __init__(self, fget=None, fset=None):
self.fget = fget
self.fset = fset
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError(f"{self.name} is read-only")
self.fset(obj, value)
def setter(self, fset):
return type(self)(self.fget, fset)
class MyStaticMethod:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
return self.func
class MyClassMethod:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if objtype is None:
objtype = type(obj)
return types.MethodType(self.func, objtype)
class Circle:
def __init__(self, radius):
self._radius = radius
@MyProperty
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("radius must be >= 0")
self._radius = value
@MyProperty
def area(self):
return round(3.14159 * self._radius ** 2, 2)
@MyStaticMethod
def unit():
return "cm"
@MyClassMethod
def unit_circle(cls):
return cls(1)
c = Circle(2)
print(c.radius, c.area)
c.radius = 3
print(c.radius, c.area)
try:
c.radius = -1
except ValueError as exc:
print("ValueError:", exc)
try:
c.area = 5
except AttributeError as exc:
print("AttributeError:", exc)
print(Circle.unit(), c.unit())
print(Circle.unit_circle().radius)2 12.57 3 28.27 ValueError: radius must be >= 0 AttributeError: area is read-only cm cm 1
Line by line
- 1
types.MethodTypelets us build a bound method by hand, whichclassmethodneeds. - 4-8
MyPropertystores the getter and optional setter function. - 10-11
__set_name__records the attribute name so error messages can mention it. - 13-18
__get__calls the getter with the instance. Access through the class returns the descriptor itself, as the realpropertydoes. - 20-23
__set__calls the setter, or raises if none was given. This is why a property with no setter is read-only. - 25-26
setterreturns a new property carrying both functions, which is how@radius.setterreplaces the attribute. - 29-34
MyStaticMethod.__get__returns the plain function, with no binding at all. - 37-45
MyClassMethod.__get__binds the function to the class (or the instance's class) withMethodType. - 48-72
Circleuses all three decorators exactly as you would use the built-in ones. - 75-86The tests: reading and writing, a validation error from the setter, a read-only
area, and calling the static and class methods through both the class and an instance.
class Greeter:
def hello(self, who):
return f"hello {who}, from {type(self).__name__}"
g = Greeter()
raw = Greeter.__dict__["hello"]
print(type(raw).__name__)
bound = raw.__get__(g, Greeter)
print(type(bound).__name__)
print(bound("Ana"))
print(bound == g.hello)
print(bound.__self__ is g, bound.__func__ is raw)
class CachedProperty:
def __init__(self, func):
self.func = func
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
value = self.func(obj)
obj.__dict__[self.name] = value
return value
class Report:
def __init__(self):
self.calls = 0
@CachedProperty
def total(self):
self.calls += 1
return sum(range(1000))
r = Report()
print(r.total, r.total, r.total)
print("computed", r.calls, "time(s)")function method hello Ana, from Greeter True True True 499500 499500 499500 computed 1 time(s)
Line by line
- 1-3A normal class with an ordinary method.
- 7-8
Greeter.__dict__['hello']is the raw function, with no binding, so its type isfunction. - 9-10Calling
__get__by hand does whatg.hellodoes automatically and returns amethodobject. - 11-13The bound method calls the function with
gfilled in; it equalsg.hello, and it exposes the instance and the original function. - 16-27
CachedPropertyis a non-data descriptor: it has no__set__. On the first read it computes the value and stores it in the instance dictionary under its own name. - 30-38
Reportcounts how often the expensive method really runs. - 41-43After the first read, the instance dictionary entry shadows the descriptor (non-data loses to instance dict), so the function is not called again.
The real property, classmethod, staticmethod and functools.cached_property are written in C or in the standard library with extra features (docstrings, __isabstractmethod__, thread safety). The ideas above are the core.
Reusable validators with descriptors
The most practical use of descriptors in everyday code is validation that you write once and reuse. Compare this with @property: a property is defined per attribute per class, so ten validated attributes mean ten getter/setter pairs. A descriptor is a class, so you instantiate it ten times in ten one-line declarations.
A good design is a small abstract base class that handles storage and the __set_name__ plumbing, with subclasses that only implement a validate method. Because validation happens in __set__, it runs on every assignment, including inside __init__, so an object can never be in an invalid state unless someone bypasses __dict__ directly.
Here I build three validators: a type checker, a positive-number checker and a choice checker. They compose naturally, and the error messages mention the attribute name, which is why __set_name__ pays off. If you prefer dataclasses with validation, the dataclasses lesson shows __post_init__ as a lighter alternative for simple cases; descriptors win when the same rule is shared across many classes.
class Validated:
"""Base class: handles naming and storage, subclasses validate."""
def __set_name__(self, owner, name):
self.name = name
self.private = "_" + name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, self.private)
def __set__(self, obj, value):
self.validate(value)
setattr(obj, self.private, value)
def validate(self, value):
raise NotImplementedError
class Typed(Validated):
def __init__(self, kind):
self.kind = kind
def validate(self, value):
if not isinstance(value, self.kind):
raise TypeError(
f"{self.name} must be {self.kind.__name__}, got {type(value).__name__}"
)
class Positive(Typed):
def __init__(self):
super().__init__((int, float))
def validate(self, value):
super().validate(value)
if value <= 0:
raise ValueError(f"{self.name} must be positive, got {value}")
class OneOf(Validated):
def __init__(self, *choices):
self.choices = choices
def validate(self, value):
if value not in self.choices:
raise ValueError(f"{self.name} must be one of {self.choices}, got {value!r}")
class Product:
title = Typed(str)
price = Positive()
size = OneOf("S", "M", "L")
def __init__(self, title, price, size):
self.title = title
self.price = price
self.size = size
p = Product("Shirt", 19.5, "M")
print(p.title, p.price, p.size)
for args in [("Shirt", -3, "M"), (123, 5, "M"), ("Shirt", 5, "XL")]:
try:
Product(*args)
except (TypeError, ValueError) as exc:
print(type(exc).__name__ + ":", exc)
p.price = 25
print(p.price)Shirt 19.5 M
ValueError: price must be positive, got -3
TypeError: title must be str, got int
ValueError: size must be one of ('S', 'M', 'L'), got 'XL'
25Line by line
- 1-17
Validatedsupplies storage (setattron a private name) and callsself.validate(value)before every write. Subclasses only overridevalidate. - 20-27
Typedrejects values of the wrong type and reports both the expected and actual type names. - 30-37
PositivereusesTypedfor the number check, then adds a range check. This shows descriptors composing through ordinary inheritance. - 40-46
OneOfallows only a fixed set of choices. - 49-57The model declares its rules in the class body.
__init__just assigns, and validation happens automatically. - 60-61A valid product is created normally.
- 63-67Three invalid inputs each fail with a clear, attribute-specific message.
- 69-70Later assignment is validated too, which a plain attribute could never do.
Because validators live on the class and store data per instance, they work with inheritance and cost almost nothing to apply. Keep them small and single-purpose.
Customising subclasses with __init_subclass__ and class decorators
Descriptors customise attributes. To customise classes themselves, many people think immediately of metaclasses, but Python 3.6 added a much simpler hook. If a class defines __init_subclass__, Python calls it automatically every time someone creates a subclass. It receives the new subclass as its first argument and may accept extra keyword arguments from the class statement, such as class Csv(Exporter, name='csv').
That is enough for registries, plugin systems and class-level validation, which are the most common reasons people reach for metaclasses. It is a normal classmethod (Python makes it implicit), it composes with multiple inheritance, and you do not suffer from metaclass conflicts. Remember to call super().__init_subclass__(**kwargs) so cooperative inheritance keeps working.
An even simpler tool is a class decorator: a function that takes a class, modifies or registers it, and returns it. @dataclass is a class decorator. Decorators are explicit at the point of use, easy to read and easy to test. The block below implements the same plugin registry both ways, so you can compare them.
class Exporter:
registry = {}
def __init_subclass__(cls, /, name=None, **kwargs):
super().__init_subclass__(**kwargs)
key = name or cls.__name__.lower()
if key in Exporter.registry:
raise ValueError(f"duplicate exporter {key!r}")
Exporter.registry[key] = cls
def export(self, rows):
raise NotImplementedError
class Csv(Exporter):
def export(self, rows):
return "\n".join(",".join(map(str, r)) for r in rows)
class Pipe(Exporter, name="pipe"):
def export(self, rows):
return "\n".join("|".join(map(str, r)) for r in rows)
rows = [(1, "a"), (2, "b")]
print(sorted(Exporter.registry))
for key in sorted(Exporter.registry):
print(f"[{key}]")
print(Exporter.registry[key]().export(rows))
try:
class Other(Exporter, name="csv"):
pass
except ValueError as exc:
print("ValueError:", exc)['csv', 'pipe'] [csv] 1,a 2,b [pipe] 1|a 2|b ValueError: duplicate exporter 'csv'
Line by line
- 1-2The base class holds a shared dictionary of registered subclasses.
- 4-9
__init_subclass__runs once for every subclass definition. It takes an optionalnamekeyword from the class statement, defaults to the lower-cased class name, and refuses duplicates. - 5Calling
super().__init_subclass__(**kwargs)keeps cooperative multiple inheritance working. - 16-23Two subclasses register themselves just by being defined; one uses the default key and one passes
name="pipe". - 26-30The registry is available immediately, so we look up a class by key and use it.
- 32-36A third subclass with a duplicate key fails at class-definition time, which is exactly when you want such errors.
REGISTRY = {}
def register(name=None):
def decorator(cls):
key = name or cls.__name__.lower()
if key in REGISTRY:
raise ValueError(f"duplicate exporter {key!r}")
REGISTRY[key] = cls
return cls
return decorator
@register()
class Csv:
def export(self, rows):
return "\n".join(",".join(map(str, r)) for r in rows)
@register("pipe")
class Pipe:
def export(self, rows):
return "\n".join("|".join(map(str, r)) for r in rows)
print(sorted(REGISTRY))
print(REGISTRY["pipe"]().export([(1, "a"), (2, "b")]))['csv', 'pipe'] 1|a 2|b
Line by line
- 1A plain module-level dictionary holds the registry; no special base class is required.
- 4-11
registeris a decorator factory. The innerdecoratorrecords the class and returns it unchanged. - 14-23Each class opts in explicitly with
@register(...). A reader sees the registration right where the class is defined. - 26-27Lookup works the same way as before.
Which should you choose? Use __init_subclass__ when every subclass of a base must participate and you want that guaranteed. Use a decorator when registration should be opt-in or when the classes do not share a base. Both are far easier to debug than a metaclass.
type() as a class factory
To understand metaclasses you first need one surprising fact: classes are objects, and they are instances of type. The class statement is not magic syntax; it is a convenient way to call type for you. The call type(name, bases, namespace) builds a brand new class from a name string, a tuple of base classes and a dictionary of attributes. Classes created this way are indistinguishable from classes written with class.
When Python executes a class statement it does roughly this: it creates an empty namespace dictionary, runs the indented body in that namespace, and then calls the metaclass (by default type) with the class name, bases and the filled namespace. The result is bound to the class name. Knowing that, you can see where each hook sits: __prepare__ creates the namespace, the body fills it, and the metaclass's __new__ and __init__ create and initialise the class.
Why would you build a class at runtime? Dynamic model generation is the common case: you read a schema (from JSON, a database or a config file) and need a class with matching fields. Libraries use this for namedtuples, enums and ORMs. Here is the manual version, followed by a small factory function that builds simple record classes from a list of field names.
def describe(self):
return f"I am a {type(self).__name__} with x={self.x}"
Point = type("Point", (), {"x": 0, "describe": describe})
p = Point()
print(p.describe())
print(Point.__name__, type(Point).__name__, type(p).__name__)
class Same:
x = 0
describe = describe
print(Same().describe())
def make_record(name, fields):
def __init__(self, *args):
if len(args) != len(fields):
raise TypeError(f"{name} expects {len(fields)} values")
for field, value in zip(fields, args):
setattr(self, field, value)
def __repr__(self):
inner = ", ".join(f"{f}={getattr(self, f)!r}" for f in fields)
return f"{name}({inner})"
return type(name, (), {"__init__": __init__, "__repr__": __repr__, "__slots__": tuple(fields)})
Person = make_record("Person", ["name", "age"])
person = Person("Ana", 30)
print(person)
print(isinstance(person, Person), type(Person).__name__)
try:
person.email = "x"
except AttributeError:
print("no extra attributes, thanks to __slots__")I am a Point with x=0 Point type Point I am a Same with x=0 Person(name='Ana', age=30) True type no extra attributes, thanks to __slots__
Line by line
- 1-2A plain function that will become a method.
- 5-6
type("Point", (), {...})builds a class namedPointwith no bases and two attributes, then we instantiate it. - 8The class's name is
Point, the class's own type istype, and the instance's type isPoint. - 11-16The equivalent
classstatement. It produces the same kind of object. - 19-31
make_recorddefines__init__and__repr__as closures over the field list and the name. - 33
type(...)is called with__slots__too, so the generated class rejects unknown attributes. - 36-37We create a class from data and use it like any other, including the usual repr.
- 38-42
isinstanceworks, and the__slots__restriction blocks stray attributes.
For ready-made dynamic classes, the standard library already offers collections.namedtuple, typing.NamedTuple, enum.Enum('Color', 'RED GREEN') and dataclasses.make_dataclass. Use those before inventing your own factory.
Writing a metaclass: __new__, __prepare__ and __call__
A metaclass is simply a class whose instances are classes. You write one by subclassing type and then request it with class Model(metaclass=Meta). Every subclass of Model inherits that metaclass automatically. The three methods worth knowing are these. __prepare__(mcs, name, bases) returns the dictionary-like object used as the class body namespace, so you can observe or restrict what the body does. __new__(mcs, name, bases, namespace) runs after the body finished and creates the class, so you can inspect or change the namespace first. __call__(cls, ...) is on the metaclass but runs when you call a class to create an instance, which lets you control instantiation (singletons, pooling and so on).
The first example uses __prepare__ to return a dictionary that raises an error if a name is defined twice in the class body. Normally, a second def with the same name silently replaces the first, a frequent source of lost tests and dead code. The second example uses __new__ to scan the namespace for descriptors and collect them into a _fields tuple, which is the pattern ORMs use. The third overrides __call__ to implement a singleton.
Read each one slowly. They are short, but each demonstrates a different stage in the class lifecycle, and together they show nearly everything a metaclass can do.
class NoDupes(dict):
def __setitem__(self, key, value):
if key in self and not key.startswith("__"):
raise TypeError(f"duplicate definition of {key!r} in class body")
super().__setitem__(key, value)
class StrictMeta(type):
@classmethod
def __prepare__(mcs, name, bases, **kwargs):
print(f" __prepare__ for {name}")
return NoDupes()
def __new__(mcs, name, bases, namespace, **kwargs):
print(f" __new__ for {name}")
return super().__new__(mcs, name, bases, dict(namespace), **kwargs)
class Good(metaclass=StrictMeta):
def run(self):
return 1
def stop(self):
return 2
try:
class Bad(metaclass=StrictMeta):
def run(self):
return 1
def run(self):
return 2
except TypeError as exc:
print("TypeError:", exc)
print(Good().run(), Good().stop())__prepare__ for Good __new__ for Good __prepare__ for Bad TypeError: duplicate definition of 'run' in class body 1 2
Line by line
- 1-5
NoDupesis a dictionary that refuses to overwrite an existing name (ignoring dunder names such as__module__). - 8-11
__prepare__is a classmethod on the metaclass. Python calls it first and uses whatever it returns as the class body namespace. - 13-15
__new__runs after the body finishes. We convert the special dictionary back to a normaldictbefore creating the class. - 18-24
Goodhas distinct names, so creation succeeds. The prints show the order: prepare first, then new. - 27-33
Baddefinesruntwice. The second definition hitsNoDupes.__setitem__while the body is still executing, so the class is never created.
class Field:
def __init__(self, kind):
self.kind = kind
def __set_name__(self, owner, name):
self.name = name
class ModelMeta(type):
def __new__(mcs, name, bases, namespace):
fields = {k: v for k, v in namespace.items() if isinstance(v, Field)}
for base in bases:
fields = {**getattr(base, "_fields", {}), **fields}
namespace["_fields"] = fields
return super().__new__(mcs, name, bases, namespace)
class Model(metaclass=ModelMeta):
def __init__(self, **kwargs):
for fname, field in self._fields.items():
value = kwargs.get(fname)
if value is not None and not isinstance(value, field.kind):
raise TypeError(f"{fname} must be {field.kind.__name__}")
setattr(self, fname, value)
def __repr__(self):
inner = ", ".join(f"{f}={getattr(self, f)!r}" for f in self._fields)
return f"{type(self).__name__}({inner})"
class User(Model):
name = Field(str)
age = Field(int)
class Admin(User):
level = Field(int)
print(list(User._fields))
print(list(Admin._fields))
print(User(name="Ana", age=30))
print(Admin(name="Bo", level=2))
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in Singleton._instances:
Singleton._instances[cls] = super().__call__(*args, **kwargs)
return Singleton._instances[cls]
class Config(metaclass=Singleton):
def __init__(self):
print(" building Config once")
self.debug = True
a = Config()
b = Config()
print(a is b)['name', 'age'] ['name', 'age', 'level'] User(name='Ana', age=30) Admin(name='Bo', age=None, level=2) building Config once True
Line by line
- 1-6A tiny descriptor-like field marker that remembers its expected type.
- 9-15
ModelMeta.__new__scans the class body forFieldobjects, merges fields inherited from base classes, and stores them in_fieldsbefore the class is built. - 18-28
Modeluses_fieldsto validate keyword arguments generically, which is how ORMs build__init__for you. - 31-37Subclasses simply declare fields; the metaclass is inherited, so
UserandAdminare processed automatically. - 40-43
_fieldsis ordered and inheritance-aware:Adminsees name, age and level. - 46-52
Singleton.__call__runs whenever you call a class using this metaclass. It creates the instance once and returns it forever after. - 55-62The
__init__message prints only once, and both names point to the same object.
Overriding __call__ on a metaclass affects every instantiation and is easy to get wrong with inheritance. A module-level instance or a factory function is usually clearer than a metaclass singleton.
Registries, plugins and when NOT to use a metaclass
A metaclass-based plugin registry is the textbook example, and it is worth seeing once: the metaclass's __new__ (or __init__) records each class as it is created. But look at the previous section's result. __init_subclass__ gave us the same registry with a normal base class, and a decorator gave it with no inheritance at all. That is the key lesson: if the job is registering, validating or slightly modifying classes at creation, you do not need a metaclass.
Metaclasses carry real costs. They make code harder to read because behaviour is invisible at the place where the class is defined. They can conflict: a class cannot combine two bases whose metaclasses are unrelated, so adopting a metaclass in your library can make it impossible for users to combine your base with another framework's. They complicate testing, type checking and documentation tools. And they tempt developers to be clever, which is expensive for the next reader.
My rule of thumb is a ladder. First try plain code and composition. Then a function or a decorator. Then __init_subclass__ or __set_name__ descriptors. Reach for a metaclass only when you must control something those cannot: the class namespace (__prepare__), the creation of the class object in ways that need to happen before it exists, or the call behaviour of the class itself (__call__), and even then ask whether a factory function would do. The block below shows the conflict problem concretely and then lists what each tool can do.
class MetaA(type):
pass
class MetaB(type):
pass
class A(metaclass=MetaA):
pass
class B(metaclass=MetaB):
pass
try:
class C(A, B):
pass
except TypeError as exc:
print("TypeError:", str(exc)[:42])
class MetaAB(MetaA, MetaB):
pass
class C2(A, B, metaclass=MetaAB):
pass
print(type(C2).__name__)
tools = [
("class decorator", "registers or edits a finished class", "easy"),
("__set_name__", "tells a descriptor its attribute name", "easy"),
("__init_subclass__", "runs code when a subclass is defined", "easy"),
("metaclass", "controls namespace, creation and calls", "hard"),
]
for name, does, difficulty in tools:
print(f"{name:18} {difficulty:5} {does}")TypeError: metaclass conflict: the metaclass of a der MetaAB class decorator easy registers or edits a finished class __set_name__ easy tells a descriptor its attribute name __init_subclass__ easy runs code when a subclass is defined metaclass hard controls namespace, creation and calls
Line by line
- 1-14Two unrelated metaclasses and two classes that use them.
- 17-21Combining
AandBfails because Python cannot decide which metaclass to use. I print only the start of the message. - 24-29The fix is to write a metaclass that inherits from both, and pass it explicitly. Possible, but awkward, and a user of your library has to know about it.
- 32The combined class's metaclass is
MetaAB. - 34-42A small comparison table of the tools from easiest to hardest, printed so you can keep it as a checklist.
If you are unsure whether you need a metaclass, you do not. Tim Peters's famous remark applies: metaclasses are deeper magic than 99 percent of users should ever worry about. If you are asking whether you need them, you do not.
Common mistakes
β Storing per-instance data on the descriptor
A descriptor object is created once per class attribute and shared by every instance. Writing self.value = value in __set__ makes all instances see the latest value. Store the data on the instance, usually in obj.__dict__ under a private key, or in a WeakKeyDictionary keyed by the instance if you cannot touch __dict__.
β Forgetting that descriptors must be class attributes
Descriptor methods are only called when the object is found on the class. Assigning a descriptor in __init__ as self.x = Field() stores an ordinary object and __get__ never runs. Declare descriptors in the class body.
β Not returning self when obj is None
When someone accesses the attribute on the class (Model.price), __get__ receives obj=None. If you do not handle that case, tools, documentation and your own tests may crash with confusing errors. Return the descriptor itself, as property does.
β Using a metaclass when __init_subclass__ or a decorator would do
Metaclasses hide behaviour and cause metaclass conflicts with other frameworks. If you only need to register a class, validate its attributes or add a method, a class decorator or __init_subclass__ is simpler, more readable and composable.
β Forgetting super().__init_subclass__(**kwargs) or super().__new__
Hooks participate in cooperative inheritance. If your __init_subclass__ or metaclass __new__ does not call the parent version, other mixins' hooks silently stop running and keyword arguments are lost. Always forward them.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. Which method makes an object a data descriptor?
__set__ or __delete__ (usually along with __get__). A class with only __get__ is a non-data descriptor.Q2. An instance's __dict__ contains x, and the class attribute x is a non-data descriptor. What does obj.x return?
Q3. What is __set_name__ for?
descriptor.__set_name__(owner, name) when the class body finishes, so descriptors do not need the name passed in by hand.Q4. What does type('Dog', (Animal,), {'sound': 'woof'}) do?
type is the class factory: name, tuple of bases, and namespace dictionary.Q5. Which is the simplest way to run code every time a subclass is defined?
__init_subclass__ is called on the parent each time a subclass is created, which covers most registry and validation needs without a metaclass.Q6. When you call Config() and Config uses a metaclass that defines __call__, what runs first?
type(Config).__call__. By default that creates the instance via __new__ and __init__, and a custom metaclass can intercept the process.Frequently asked questions
Is @property a descriptor?
+Yes. property is a built-in class that implements __get__, __set__ and __delete__, so it is a data descriptor. Even a property with no setter blocks assignment because its __set__ raises AttributeError.
Do I need to learn metaclasses to be a good Python programmer?
+No. Most professional Python code never defines a metaclass. It is worth understanding so you can read framework code and decide wisely, but descriptors, decorators and __init_subclass__ cover nearly every practical need.
What is the difference between __getattr__ and __getattribute__?
+__getattribute__ runs on every attribute access and is where descriptor lookup happens. __getattr__ is only a fallback called when normal lookup fails. Overriding __getattribute__ is risky because mistakes cause infinite recursion.
Can a descriptor work with __slots__?
+Yes, and __slots__ itself uses descriptors: each slot becomes a member descriptor on the class. Your own descriptor can coexist, but you must store data in slots or another place, since there is no instance __dict__ to write to.
How do descriptors relate to dataclasses and type hints?
+A dataclass field can have a descriptor as its default, which is an advanced pattern. For most validation, __post_init__ is simpler; see the dataclasses and type hints lessons. Descriptors shine when one rule is reused across many classes.
Key takeaways
- βA descriptor is an object on a class with
__get__,__set__or__delete__; Python calls those methods during attribute access. - βData descriptors beat the instance
__dict__; non-data descriptors lose to it. Functions and cached properties are non-data,propertyis data. - β
property,classmethod,staticmethodand bound methods are all descriptors, and you can rebuild them in a few lines. - βStore per-instance values on the instance (not on the descriptor), and use
__set_name__so descriptors know their attribute name. - βClasses are instances of
type;type(name, bases, namespace)builds a class, and a metaclass customises__prepare__,__new__and__call__. - βPrefer decorators,
__set_name__and__init_subclass__over metaclasses; use a metaclass only when nothing simpler can control what you need.