473,704 Members | 6,025 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python 2.6 / 3.0: 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__'
Hmmm... I can get this working with Python 2.6 with:

if '__lt__' in dir(cls):

The default implementation of '__lt__' doesn't appear in the dir of
classes. However this fails with Python 3 where the default
implementation *does* appear in the output of 'dir'. Any suggestions?

Michael Foord
--
http://www.ironpythoninaction.com/
Oct 5 '08 #1
8 2612
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...)

Some things I have tried:
>X.__lt__.__sel f__
<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__.__fun c__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'method-wrapper' object has no attribute '__func__'
Hmmm... I can get this working with Python 2.6 with:

if '__lt__' in dir(cls):

The default implementation of '__lt__' doesn't appear in the dir of
classes. However this fails with Python 3 where the default
implementation *does* appear in the output of 'dir'. Any suggestions?
Methods are objects. How do you know if two references refer to the
same object? You use "is":

X.__lt__ is object.__lt__
Oct 6 '08 #2
On Oct 5, 7:13*pm, MRAB <goo...@mrabarn ett.plus.comwro te:
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.
Hmmm... I can get this working with Python 2.6 with:

Methods are objects. How do you know if two references refer to the
same object? You use "is":

X.__lt__ is object.__lt__
That doesn't work for me.
>>class A( object ):
.... pass
....
>>class B( A ):
.... def __lt__( self, other ):
.... return self
....
>>a= A()
b= B()
B.__lt__ is object.__lt__
False
>>A.__lt__ is object.__lt__
False
>>>
Further, it's been noted before that

A().meth is not A().meth
Oct 6 '08 #3
On Oct 6, 1:13 am, MRAB <goo...@mrabarn ett.plus.comwro te:
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...)
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__'
Hmmm... I can get this working with Python 2.6 with:
if '__lt__' in dir(cls):
The default implementation of '__lt__' doesn't appear in the dir of
classes. However this fails with Python 3 where the default
implementation *does* appear in the output of 'dir'. Any suggestions?

Methods are objects. How do you know if two references refer to the
same object? You use "is":

X.__lt__ is object.__lt__
Didn't you see that even an equality test fails - so they are not the
same (that being the problem)...

They are unbound method objects - in Python 3 the unbound method has
gone away, so the problem is with Python 2.6.

Michael
--
http://www.ironpythoninaction.com/
Oct 6 '08 #4
On Oct 6, 4:30*am, Fuzzyman <fuzzy...@gmail .comwrote:
On Oct 6, 1:13 am, MRAB <goo...@mrabarn ett.plus.comwro te:
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...)
Some things I have tried:
>X.__lt__.__sel f__
<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__.__fun c__
Traceback (most recent call last):
* File "<stdin>", line 1, in <module>
AttributeError: 'method-wrapper' object has no attribute '__func__'
Hmmm... I can get this working with Python 2.6 with:
if '__lt__' in dir(cls):
The default implementation of '__lt__' doesn't appear in the dir of
classes. However this fails with Python 3 where the default
implementation *does* appear in the output of 'dir'. Any suggestions?
Methods are objects. How do you know if two references refer to the
same object? You use "is":
X.__lt__ is object.__lt__

Didn't you see that even an equality test fails - so they are not the
same (that being the problem)...

They are unbound method objects - in Python 3 the unbound method has
gone away, so the problem is with Python 2.6.

Michael
--http://www.ironpythoni naction.com/
Not tested extensively.

class NoLTException( Exception ): pass

class NoLT( object ):
def __lt__( self, other ):
raise NoLTException()

class A( NoLT ):
pass

class B( A ):
def __lt__( self, other ):
return self

def test_lt( obj ):
try:
obj.__lt__( None )
except NoLTException:
return False
except:
pass
return True
>>a= A()
b= B()
test_lt( a )
False
>>test_lt( b )
True
>>>
This method won't work for arbitrary classes, only ones that you
control, that inherit from 'NoLT'. The 'test_lt' function works by
trying to call '__lt__' on its argument. The parameter to it doesn't
matter because of what happens next. If '__lt__' raises a
NoLTException, you know it was inherited from NoLT. Otherwise, even
if another exception occurs, the object you know has '__lt__'.

It's a very object oriented solution. Essentially you're inheriting
all the classes that you want to fail, from a class that does.
Oct 6 '08 #5
On Oct 6, 7:01*pm, "Aaron \"Castironpi \" Brady" <castiro...@gma il.com>
wrote:
On Oct 6, 4:30*am, Fuzzyman <fuzzy...@gmail .comwrote:
On Oct 6, 1:13 am, MRAB <goo...@mrabarn ett.plus.comwro te:
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...)
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__'
Hmmm... I can get this working with Python 2.6 with:
if '__lt__' in dir(cls):
The default implementation of '__lt__' doesn't appear in the dir of
classes. However this fails with Python 3 where the default
implementation *does* appear in the output of 'dir'. Any suggestions?
Methods are objects. How do you know if two references refer to the
same object? You use "is":
X.__lt__ is object.__lt__
Didn't you see that even an equality test fails - so they are not the
same (that being the problem)...
They are unbound method objects - in Python 3 the unbound method has
gone away, so the problem is with Python 2.6.
Michael
--http://www.ironpythoni naction.com/

Not tested extensively.

class NoLTException( Exception ): pass

class NoLT( object ):
* * def __lt__( self, other ):
* * * * * * raise NoLTException()

class A( NoLT ):
* * pass

class B( A ):
* * def __lt__( self, other ):
* * * * * * return self

def test_lt( obj ):
* * try:
* * * * * * obj.__lt__( None )
* * except NoLTException:
* * * * * * return False
* * except:
* * * * * * pass
* * return True
>a= A()
b= B()
test_lt( a )
False
>test_lt( b )
True

This method won't work for arbitrary classes, only ones that you
control, that inherit from 'NoLT'. *The 'test_lt' function works by
trying to call '__lt__' on its argument. *The parameter to it doesn't
matter because of what happens next. *If '__lt__' raises a
NoLTException, you know it was inherited from NoLT. *Otherwise, even
if another exception occurs, the object you know has '__lt__'.

It's a very object oriented solution. *Essentially you're inheriting
all the classes that you want to fail, from a class that does.
But not a very good solution to the problem...

The specific problem is to determine if an arbitrary class implements
a specified comparison method. The general problem (that gives rise to
the specific problem) is to write a class decorator that can implement
all comparison methods from a class that implements only one.

See: http://code.activestate.com/recipes/576529/

Michael
--
http://www.ironpythoninaction.com/
Oct 6 '08 #6
On Oct 6, 1:17*pm, Fuzzyman <fuzzy...@gmail .comwrote:
On Oct 6, 7:01*pm, "Aaron \"Castironpi \" Brady" <castiro...@gma il.com>
wrote:
It's a very object oriented solution. *Essentially you're inheriting
all the classes that you want to fail, from a class that does.

But not a very good solution to the problem...

The specific problem is to determine if an arbitrary class implements
a specified comparison method. The general problem (that gives rise to
the specific problem) is to write a class decorator that can implement
all comparison methods from a class that implements only one.

See:http://code.activestate.com/recipes/576529/

Michael
--http://www.ironpythoni naction.com/
Nope, I'm out of ideas, I'm afraid.
Oct 6 '08 #7
2008/10/5 Fuzzyman <fu******@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.ismetho d 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.ismet hod(C().__str__ )
False
>>inspect.ismet hod(D().__str__ )
True
>>inspect.ismet hod(E().__str__ )
True
>>>
C().__str__.i m_class
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'method-wrapper' object has no attribute 'im_class'
>>D().__str__.i m_class
<class '__main__.D'>
>>E().__str__.i m_class
<class '__main__.E'>
Cheers,
.peke
Oct 6 '08 #8
2008/10/7 Pekka Laukkanen <pe**@iki.fi> :
2008/10/5 Fuzzyman <fu******@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.ismetho d 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.isme thod(C().__str_ _)
False
>>>inspect.isme thod(D().__str_ _)
True
>>>inspect.isme thod(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
Oct 6 '08 #9

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
4066
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
10755
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
11
1653
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
900
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
8766
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
9134
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9025
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
7887
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
6604
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
5930
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
4438
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
2478
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2078
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.