Python 2.6: Determining if a method is inherited

Fuzzyman fuzzyman at gmail.com
Sun Oct 5 17:48:13 EDT 2008


On Oct 5, 8:15 pm, dialUAZ###UZ#$AAt... at gWARAmail.com (Valentino
Volonghi aka Dialtone) wrote:
> Fuzzyman <fuzzy... at gmail.com> wrote:
> > So how do I tell if the X.__lt__ is inherited from object? I can look
>
> I don't have python 2.6 installed so I can't try but what I think could
> work is:
>
> >>> class Foo(object):
>
> ...     def hello(self):
> ...         pass
> ...>>> class Bla(Foo):
>
> ...     def hello(self):
> ...         pass
> ...>>> class Baz(Foo):
>
> ...     pass
> ...>>> Baz.hello.im_func
>
> <function hello at 0x2b1630>>>> Bla.hello.im_func
>
> <function hello at 0x2b1670>>>> Foo.hello.im_func
>
> <function hello at 0x2b1630>>>> Foo.hello.im_func is Baz.hello.im_func
> True
> >>> Foo.hello.im_func is Bla.hello.im_func
>
> False
>


Nope:

Python 2.6 (trunk:66714:66715M, Oct  1 2008, 18:36:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class X(object): pass
...
>>> X.__lt__.im_func
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'method-wrapper' object has no attribute 'im_func'
>>>

What I went with in the end:

import sys as _sys

if _sys.version_info[0] == 3:
    def _has_method(cls, name):
        for B in cls.__mro__:
            if B is object:
                continue
            if name in B.__dict__:
                return True
        return False
else:
    def _has_method(cls, name):
        for B in cls.mro():
            if B is object:
                continue
            if name in B.__dict__:
                return True
        return False

See this page for why I needed it:

http://www.voidspace.org.uk/python/weblog/arch_d7_2008_10_04.shtml#e1018

Michael

> Which to me also makes sense. If it's inherited I expect it to be the
> very same function object of one of the bases (which you can get with
> inspect.getmro(Clazz)). On the other end if you override it it's not the
> same function object so it won't return True when applied to 'is'.
>
> HTH
>
> --
> Valentino Volonghi aka Dialtonehttp://stacktrace.it-- Aperiodico di resistenza informatica
> Blog:http://www.twisted.it/
> Public Beta:http://www.adroll.com/




More information about the Python-list mailing list