473,729 Members | 2,235 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python 2.6: Determining if a method is inherited

Hello all,

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...)

Some things I have tried:

>>X.__lt__.__se lf__
<class '__main__.X'>
>>dir(X.__lt_ _)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__',
'__format__', '__getattribute __', '__hash__', '__init__', '__name__',
'__new__', '__objclass__', '__reduce__', '__reduce_ex__' , '__repr__',
'__self__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook __']
>>X.__lt__.__fu nc__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'method-wrapper' object has no attribute '__func__'

Michael Foord
--
http://www.ironpythoninaction.com/
Oct 5 '08 #1
11 1656
Fuzzyman <fu******@gmail .comwrote:
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_fu nc
True
>>Foo.hello.im_ func is Bla.hello.im_fu nc
False

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 Dialtone
http://stacktrace.it -- Aperiodico di resistenza informatica
Blog: http://www.twisted.it/
Public Beta: http://www.adroll.com/
Oct 5 '08 #2
Fuzzyman wrote:
Hello all,

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...)
They're of different types. I'm not sure how much you could use that,
or how reliable it is.
>>class A( object ):
.... pass
....
>>class B( object ):
.... def __lt__( self, other ):
.... pass
....
>>hasattr( A, '__lt__' )
True
>>hasattr( B, '__lt__' )
True
>>A.__lt__
<method-wrapper '__lt__' of type object at 0x00B81D48>
>>B.__lt__
<unbound method B.__lt__>
>>>
Oct 5 '08 #3
On Oct 5, 8:15*pm, dialUAZ###UZ#$A At...@gWARAmail .com (Valentino
Volonghi aka Dialtone) wrote:
Fuzzyman <fuzzy...@gmail .comwrote:
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_fu nc
True
>Foo.hello.im_f unc is Bla.hello.im_fu nc

False

Nope:

Python 2.6 (trunk:66714:66 715M, 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_f unc
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_in fo[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/w...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/
Oct 5 '08 #4
Fuzzyman wrote:
Hello all,

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
In 3.0, the test returns true because function attributes only get
wrapped when bound. In the meanwhile, " 'object' in repr(X.__lt__)"
should do it for you.

tjr

Oct 5 '08 #5
Terry Reedy wrote:
In 3.0, the test returns true because function attributes only get
wrapped when bound. In the meanwhile, " 'object' in repr(X.__lt__)"
should do it for you.
This session should give you some hints how to archive your goal :)
Have fun!
>>import types
class A(object):
.... def __lt__(self):
.... pass
....
>>isinstance(A. __lt__, types.MethodTyp e)
True
>>isinstance(A. __gt__, types.MethodTyp e)
False
>>type(A.__lt__ )
<type 'instancemethod '>
>>type(A.__gt__ )
<type 'method-wrapper'>
>>type(A.__str_ _)
<type 'wrapper_descri ptor'>
>>type(A.__new_ _)
<type 'builtin_functi on_or_method'>
>>A.__lt__.im_f unc
<function __lt__ at 0x7f03f9298500>
>>A.__lt__.im_f unc == A.__lt__.im_fun c
True
>>A.__gt__.im_f unc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'method-wrapper' object has no attribute 'im_func'

Oct 6 '08 #6
On Oct 5, 11:54 pm, Terry Reedy <tjre...@udel.e duwrote:
Fuzzyman wrote:
Hello all,
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

In 3.0, the test returns true because function attributes only get
wrapped when bound. In the meanwhile, " 'object' in repr(X.__lt__)"
should do it for you.

So long as its never used on a class with 'object' in the name.
Doesn't sound like a particularly *good* solution to me. :-)

Michael
tjr
--
http://www.ironpythoninaction.com/
Oct 6 '08 #7
On Oct 6, 7:16 am, Christian Heimes <li...@cheimes. dewrote:
Terry Reedy wrote:
In 3.0, the test returns true because function attributes only get
wrapped when bound. In the meanwhile, " 'object' in repr(X.__lt__)"
should do it for you.

This session should give you some hints how to archive your goal :)
Have fun!
>>import types
>>class A(object):
... def __lt__(self):
... pass
...
>>isinstance(A. __lt__, types.MethodTyp e)
True
>>isinstance(A. __gt__, types.MethodTyp e)
False
>>type(A.__lt__ )
<type 'instancemethod '>
>>type(A.__gt__ )
<type 'method-wrapper'>
>>type(A.__str_ _)
<type 'wrapper_descri ptor'>
>>type(A.__new_ _)
<type 'builtin_functi on_or_method'>
>>A.__lt__.im_f unc
<function __lt__ at 0x7f03f9298500>
>>A.__lt__.im_f unc == A.__lt__.im_fun c
True
>>A.__gt__.im_f unc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'method-wrapper' object has no attribute 'im_func'
However - I need to detect whether a method is inherited from
*object*. All those differences you have shown behave identically if
the class inherits from 'int'.

I am trying to detect explicit implementation of comparison methods -
so there is a big difference between inheriting from int and
inheriting from object (meaningful comparison methods existing on one
and not the other).

What I went for in the end:

import sys as _sys

if _sys.version_in fo[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/w...04.shtml#e1018

Michael

--
http://www.ironpythoninaction.com/
Oct 6 '08 #8
Fuzzyman wrote:
On Oct 5, 11:54 pm, Terry Reedy <tjre...@udel.e duwrote:
>Fuzzyman wrote:
>>Hello all,
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
In 3.0, the test returns true because function attributes only get
wrapped when bound. In the meanwhile, " 'object' in repr(X.__lt__)"
should do it for you.
So long as its never used on a class with 'object' in the name.
Doesn't sound like a particularly *good* solution to me. :-)
From what you posted, 'type object at' should work.

Oct 6 '08 #9
On Oct 6, 7:02*pm, Terry Reedy <tjre...@udel.e duwrote:
Fuzzyman wrote:
On Oct 5, 11:54 pm, Terry Reedy <tjre...@udel.e duwrote:
Fuzzyman wrote:
Hello all,
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
In 3.0, the test returns true because function attributes only get
wrapped when bound. *In the meanwhile, " 'object' in repr(X.__lt__)"
should do it for you.
So long as its never used on a class with 'object' in the name.
Doesn't sound like a particularly *good* solution to me. :-)

*From what you posted, 'type object at' should work.
It's still a hack...
Oct 6 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
3689
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. Andrew dalke@dalkescientific.com
86
4076
by: Matthias Kaeppler | last post by:
Hi, sorry for my ignorance, but after reading the Python tutorial on python.org, I'm sort of, well surprised about the lack of OOP capabilities in python. Honestly, I don't even see the point at all of how OO actually works in Python. For one, is there any good reason why I should ever inherit from a class? ^^ There is no functionality to check if a subclass correctly implements an inherited interface and polymorphism seems to be...
267
10777
by: Xah Lee | last post by:
Python, Lambda, and Guido van Rossum Xah Lee, 2006-05-05 In this post, i'd like to deconstruct one of Guido's recent blog about lambda in Python. In Guido's blog written in 2006-02-10 at http://www.artima.com/weblogs/viewpost.jsp?thread=147358
8
2614
by: Fuzzyman | last post by:
Hello all, 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
0
902
by: Fuzzyman | last post by:
Hello all, Sorry - my messages aren't showing up via google groups, so I'm kind of posting on faith... Anyway, I solved my problem (I think)... import sys if sys.version_info == 3:
0
8913
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6016
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2162
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.