How to get a reference of the 'owner' class to which a method belongs in Python 3.X?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Mar 17 06:01:37 EDT 2012


On Fri, 16 Mar 2012 22:30:34 -0700, Cosmia Luna wrote:

> I'm porting my existing work to Python 3.X, but...
> 
> class Foo:
>     def bar(self):
>         pass
> 
> mthd = Foo.bar
> 
> assert mthd.im_class is Foo # this does not work in py3k
> 
> So, how can I get a reference to Foo? This is important when writing
> decorators, the only way I can think out is:

I don't believe you can get a reference to Foo just by inspecting the 
function object Foo.bar. (In Python 2.x, Foo.bar would be an unbound 
method, but they no longer exist in Python 3.x.)


> class Foo:
>     def bar(self):
>         'Foo' # manually declare the owner class 
>         pass

A better approach might be to inject a reference to the class after the 
event, using a class decorator:

function = type(lambda: None)

def inject_class(cls):
    for name, obj in vars(cls).items():
        if type(obj) is function:
            obj.owner_class = cls
    return cls


And in use:

py> @inject_class
... class Test:
...     a = 1
...     b = 2
...     def method(self, x):
...         return (x, self)
...
py> Test.a
1
py> Test.method
<function method at 0xb7b21bec>
py> Test.method.owner_class is Test
True


Does this help?



-- 
Steven



More information about the Python-list mailing list