Sub topic 14
Lookup on classes and metaclasses
This chapter assumes you know the instance lookup order from the previous chapters: data descriptor, then instance __dict__, then non-data descriptor or class attribute. It also assumes you can read a simple metaclass declaration such as class Model(metaclass=Meta).
Who handles `C.name`
obj.name calls type(obj).__getattribute__. When obj is itself a class, type(obj) is its metaclass, which is type unless you set another one. The method that runs is therefore type.__getattribute__. It follows a similar order to object.__getattribute__, with two differences:
- The class's own MRO plays the role the instance
__dict__plays for instances. - The metaclass plays the role the class plays for instances.
The order for C.name is:
- Search the metaclass's MRO for
name. If you find a data descriptor, call its__get__(C, Meta)and return the result. - Search
C.__mro__forname, checking each class's__dict__. If you find a value that has__get__, returnvalue.__get__(None, C). Otherwise return the value itself. - If step 1 found a non-data descriptor, call its
__get__(C, Meta). If it found a plain attribute, return it. - Otherwise raise
AttributeError. The metaclass's__getattr__, if it has one, runs as the fallback.
What `__get__` receives
In step 2 the descriptor gets None as obj. This is why descriptors usually start with if obj is None: return self. The second argument is the class you accessed the attribute through, not the class that defines it.
class Show:
def __get__(self, obj, objtype=None):
return f"obj={obj!r}, objtype={objtype.__name__}"
class K:
s = Show()
class Sub(K):
pass
print(K.s) # obj=None, objtype=K
print(Sub.s) # obj=None, objtype=SubFunctions follow the same rule. In Python 3, C.greet calls greet.__get__(None, C), which returns the plain function with no bound method. This is why you can call C.greet(instance) directly.
Metaclass attributes
An attribute defined on a metaclass is visible on the class but not on its instances. Instance lookup searches type(obj).__mro__, which contains the class and its bases and never the metaclass.
class Meta(type):
@property
def registry_name(cls):
return cls.__name__.lower() + "_registry"
def describe(cls):
return f"class {cls.__name__}"
class Model(metaclass=Meta):
registry_name = "class attribute"
label = "model label"
m = Model()
print(Model.registry_name) # model_registry
print(Model.describe()) # class Model
print(Model.label) # model label
print(m.registry_name) # class attribute
try:
m.describe
except AttributeError:
print("instances cannot see metaclass attributes")Model.registry_name returns the metaclass value even though Model.__dict__ has the same name. A property is a data descriptor, and step 1 checks it before the class's own dictionary. If describe were a data descriptor, it would win in the same way. Because it is a plain function, a non-data descriptor, a same-named entry in Model.__dict__ would take priority.
Practical consequences
| Expression | Searches | Descriptor call |
|---|---|---|
| `obj.name` | `type(obj).__mro__`, then `obj.__dict__` | `__get__(obj, type(obj))` |
| `C.name` | metaclass MRO, then `C.__mro__` | `__get__(None, C)` for class entries |
| `C.name` for metaclass entries | metaclass MRO | `__get__(C, Meta)` |
Exercise
Given class Meta(type): x = property(lambda cls: "meta") and class A(metaclass=Meta): x = "own", what do A.x and A().x return, and why?
Show answer
A.x returns "meta". The property on the metaclass is a data descriptor, so type.__getattribute__ uses it before searching A.__mro__. A().x returns "own". Instance lookup searches A.__mro__ and never looks at the metaclass.