Python 2.6 / 3.0: Determining if a method is inherited

Pekka Laukkanen peke at iki.fi
Mon Oct 6 19:50:26 EDT 2008


2008/10/7 Pekka Laukkanen <peke at iki.fi>:
> 2008/10/5 Fuzzyman <fuzzyman at gmail.com>:
>> I may well be being dumb (it has happened before), but I'm struggling
>> to fix some code breakage with Python 2.6.
>>
>> I have some code that looks for the '__lt__' method on a class:
>>
>> if hasattr(clr, '__lt__'):
>>
>> However - in Python 2.6 object has grown a default implementation of
>> '__lt__', so this test always returns True.
>>
>>>>> class X(object): pass
>> ...
>>>>> X.__lt__
>> <method-wrapper '__lt__' of type object at 0xa15cf0>
>>>>> X.__lt__ == object.__lt__
>> False
>>
>> So how do I tell if the X.__lt__ is inherited from object? I can look
>> in the '__dict__' of the class - but that doesn't tell me if X
>> inherits '__lt__' from a base class other than object. (Looking inside
>> the method wrapper repr with a regex is not an acceptable answer...)
>
> I don't have Python 2.6 available, but if __lt__ on it works similarly
> as __str__ on Python 2.5, you might be able to achieve this either
> with inspect.ismethod or by checking methods' im_class attribute
> directly:
>
>>>> class C(object):
> ...     pass
> ...
>>>> class D(object):
> ...     def __str__(self):
> ...         return ''
> ...
>>>> class E(D):
> ...     pass
> ...
>>>> import inspect
>>>> inspect.ismethod(C().__str__)
> False
>>>> inspect.ismethod(D().__str__)
> True
>>>> inspect.ismethod(E().__str__)
> True
>>>>
>>>> C().__str__.im_class
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> AttributeError: 'method-wrapper' object has no attribute 'im_class'
>>>> D().__str__.im_class
> <class '__main__.D'>
>>>> E().__str__.im_class
> <class '__main__.E'>

Ooops, didn't notice this was suggested already. One more attempt,
hopefully this is unique. =)

>>> C().__str__.__objclass__
<type 'object'>
>>> D().__str__.__objclass__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__objclass__'
>>> 'spam'.__str__.__objclass__
<type 'str'>

Someone who actually knows what __objclas__ does can probably comment
does this make any sense in your case.

Cheers,
     .peke



More information about the Python-list mailing list