Sub topic 14
Lookup on classes and metaclasses
This chapter assumes you know the instance lookup order from earlier in the series: data descriptor, then instance __dict__, then non-data descriptor or plain class attribute, then __getattr__. It also assumes you are comfortable with the MRO (method resolution order) and have seen a metaclass declared with class C(metaclass=M).
Two different algorithms
When you write obj.name, Python calls type(obj).__getattribute__. For an ordinary object that is object.__getattribute__, the algorithm you already know.
When the object is itself a class, type(obj) is its metaclass, which is type unless you chose another. So C.name runs type.__getattribute__(C, "name"). This is a separate algorithm. It searches two places: the class's own MRO and the metaclass's MRO.
| Expression | Hook that runs | Namespaces searched |
|---|---|---|
| `obj.name` | `type(obj).__getattribute__` (usually `object`'s) | `type(obj).__mro__`, then `obj.__dict__` |
| `C.name` | `type(C).__getattribute__` (usually `type`'s) | `type(C).__mro__`, then `C.__mro__` |
The role of the __dict__ changes. For an instance, the instance __dict__ sits between the two descriptor kinds. For a class, the search of C.__mro__ takes that place, and it goes through every class __dict__ in the chain, not just C's own.
The lookup order for C.name
type.__getattribute__ works in this order:
- Search the metaclass MRO (
type(C).__mro__) forname. Call the resultmeta_attr. - If
meta_attris a data descriptor, returnmeta_attr.__get__(C, type(C)). - Search
C.__mro__forname. If found and it has__get__, returnattr.__get__(None, C). Otherwise return the object as is. - If step 1 found a non-data descriptor, return its
__get__(C, type(C)). If step 1 found a plain value, return it. - Raise
AttributeError. If the metaclass defines__getattr__, Python calls it first.
What each layer can see
Attributes defined on the metaclass are visible on the class but not on its instances. Instance lookup never searches the metaclass.
class Meta(type):
registry_name = "from metaclass"
@property
def table(cls):
return cls.__name__.lower() + "s"
class Model(metaclass=Meta):
label = "from class"
print(Model.label) # from class
print(Model.registry_name) # from metaclass
print(Model.table) # models
m = Model()
print(m.label) # from class
try:
m.table
except AttributeError:
print("instances cannot see metaclass attributes")table is a property stored on Meta. Accessing it through Model finds a data descriptor in step 2, and Model is passed to the getter as cls. This is how you give a class computed attributes of its own. Putting the property on the class instead would only affect its instances.
Precedence when both layers define the name
If the same name appears in both namespaces, the metaclass wins only when its attribute is a data descriptor.
class Meta(type):
data = property(lambda cls: "meta data descriptor")
plain = "meta plain"
class K(metaclass=Meta):
data = "class data"
plain = "class plain"
print(K.data) # meta data descriptor
print(K.plain) # class plain
print(K().data) # class dataThis is the same rule as for instances, applied one level up. The metaclass plays the role of the type, and the class plays the role of the instance. A data descriptor on the metaclass beats the class namespace. A plain value on the metaclass loses to the class namespace.
The last line shows that the instance K() ignores Meta completely.
What `__get__` receives on a class access
When a descriptor is found in the class's own MRO, Python calls __get__(None, C). The first argument is None because there is no instance. The second is the class you accessed, even if the descriptor was defined on a base class.
class Show:
def __get__(self, obj, objtype=None):
print(f"obj is None: {obj is None}, objtype={objtype.__name__}")
return 42
class Base:
x = Show()
class Derived(Base):
pass
Base.x # obj is None: True, objtype=Base
Derived.x # obj is None: True, objtype=Derived
Derived().x # obj is None: False, objtype=DerivedThis is why the if obj is None: return self convention appears in descriptors such as Positive. Without it, Item.price would try to read a per-instance value from None and fail. With it, accessing the descriptor through the class returns the descriptor object, which helps introspection and documentation tools.
Built-in descriptors use the same hook:
- A function's
__get__(None, C)returns the plain function, which is whyC.methodis not a bound method. property.__get__(None, C)returns thepropertyobject itself.classmethod.__get__(None, C)returns a method bound toC.staticmethod.__get__always returns the wrapped function.
A pure-Python model
This sketch models the steps above, leaving out the metaclass __getattr__ fallback. It reuses the descriptor test from the instance model.
_missing = object()
def find(owner, name):
for base in owner.__mro__:
if name in vars(base):
return vars(base)[name]
return _missing
def is_data(attr):
t = type(attr)
return hasattr(t, "__get__") and (
hasattr(t, "__set__") or hasattr(t, "__delete__")
)
def class_lookup(cls, name):
meta = type(cls)
meta_attr = find(meta, name)
if meta_attr is not _missing and is_data(meta_attr):
return type(meta_attr).__get__(meta_attr, cls, meta)
own = find(cls, name)
if own is not _missing:
t = type(own)
if hasattr(t, "__get__"):
return t.__get__(own, None, cls)
return own
if meta_attr is not _missing:
t = type(meta_attr)
if hasattr(t, "__get__"):
return t.__get__(meta_attr, cls, meta)
return meta_attr
raise AttributeError(f"type object {cls.__name__!r} has no attribute {name!r}")
class Meta(type):
data = property(lambda cls: "meta data descriptor")
plain = "meta plain"
class K(metaclass=Meta):
data = "class data"
plain = "class plain"
def method(self):
return "m"
for attr in ("data", "plain", "method", "__name__"):
assert class_lookup(K, attr) == getattr(K, attr)
print("model matches the real lookup")The __name__ check shows the model also covers built-in behavior. __name__ is a data descriptor (a getset_descriptor) on type, so it wins in step 2.
Metaclass `__getattr__`
If both searches fail, Python calls __getattr__ found on the metaclass. A __getattr__ defined in the class body only affects instances. It does not affect C.missing.
class Meta(type):
def __getattr__(cls, name):
if name.startswith("find_by_"):
return f"query on {name[len('find_by_'):]}"
raise AttributeError(f"{cls.__name__} has no attribute {name!r}")
class User(metaclass=Meta):
pass
print(User.find_by_email) # query on email
try:
User().find_by_email
except AttributeError:
print("instance lookup does not use the metaclass")Always raise AttributeError for names you do not handle. Otherwise hasattr(User, "anything") returns True, and tools that probe classes, such as copy and pickle, can misbehave.
Assignment on classes is different
Reading C.name consults descriptors in the class. Writing C.name = value does not. type.__setattr__ checks only the metaclass for a data descriptor, then stores the value in C.__dict__.
class Positive:
def __set_name__(self, owner, name):
self.private_name = "_" + name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, self.private_name)
def __set__(self, obj, value):
if value <= 0:
raise ValueError("must be positive")
setattr(obj, self.private_name, value)
class Item:
price = Positive()
Item.price = -5 # no validation: the descriptor is replaced
print(Item.price) # -5
print(type(Item.__dict__["price"]).__name__) # intThe assignment silently replaced the descriptor. To protect a class-level name from assignment, put a data descriptor on the metaclass:
class Meta(type):
@property
def version(cls):
return 1
class Model(metaclass=Meta):
pass
print(Model.version) # 1
try:
Model.version = 2
except AttributeError:
print("blocked by the metaclass data descriptor")Debugging tips
- To see where a class attribute comes from, search both MROs by hand:
[b for b in type(C).__mro__ + C.__mro__ if "name" in vars(b)]. C.__dict__["name"]returns the raw descriptor without calling__get__.C.namegoes through the full lookup.- If a class attribute is "invisible" on instances, check whether it lives on the metaclass.
- Special methods such as
len(x)andx[0]are looked up ontype(x), bypassing the instance. For a class, that meansC[int]uses a__getitem__defined on the metaclass, andC()uses the metaclass's__call__.
Exercise
A metaclass Meta(type) sets tag = "meta". Class A uses metaclass=Meta and defines no tag. Class B inherits from A. What does B.tag return, and what does B().tag do? Explain using the search order.
Show answer
B.tag returns "meta". B's metaclass is Meta, inherited from A, and type._getattribute searches B's MRO (B, A, object) and then the metaclass MRO. Nothing is found in B's MRO, so the plain value from Meta is returned in step 4. B().tag raises AttributeError, because instance lookup searches only B, A and object, plus the instance dict_, and never consults the metaclass.
Exercise
A class Config has a data descriptor port = Port(), where Port defines _get and set_ and validates the value. The line Config.port = "abc" runs without error. Why does the validation not run, and how would you make assignment on the class itself fail?
Show answer
Assignment on a class goes through type._setattr, which looks for a data descriptor only on the metaclass, not in the class's own namespace. The Port.set method is used only for assignments on instances. So Config.port = "abc" replaces the descriptor in Config.dict. To block or validate class-level assignment, define a data descriptor (for example a property, or a descriptor with set_) with that name on a metaclass, and create Config with that metaclass.