Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are function attributes transparently viewed by a method

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?

like image 240
Mad Physicist Avatar asked Mar 05 '23 03:03

Mad Physicist


1 Answers

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.

like image 111
user2357112 supports Monica Avatar answered Mar 25 '23 00:03

user2357112 supports Monica