I recently wrote a number of functions that needed a marker attribute:
def fn1(): pass
fn1.mark = True
The actual marking was done by a decorator, but that it neither here nor there. My worry was that when I marked methods in a class in the same way, the marker would not be visible when the method was bound:
class A:
def meth1(): pass
meth1.mark = True
But in fact the attribute was visible just fine:
>>> fn1.mark
True
>>> A.meth1.mark
True
>>> A().meth1.mark
True
However, the attribute can not be assigned to or deleted in the bound method, as it can be in the function:
>>> A().meth1.mark = False
AttributeError: 'method' object has no attribute 'mark'
>>> del A().meth1.mark
AttributeError: 'method' object has no attribute 'mark'
How are the attributes of a method made visible when it is bound?
Method objects implement __getattribute__
to delegate attribute access for unknown attributes to the underlying function object. They don't delegate __setattr__
, though, which is why the assignment failed. If you want to see the code, it's method_getattro
in Objects/classobject.c
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With