Issue
Ran into this problem (in Python 2.7.5) with a little typo:
def foo(): return 3
if foo > 8:
launch_the_nukes()
Dang it, I accidentally exploded the Moon.
My understanding is that E > F
is equivalent to (E).__gt__(F)
and for well behaved classes (such as builtins) equivalent to (F).__lt__(E)
.
If there's no __lt__
or __gt__
operators then I think Python uses __cmp__
.
But, none of these methods work with function
objects while the <
and >
operators do work. What goes on under the hood that makes this happen?
>>> foo > 9e9
True
>>> (foo).__gt__(9e9)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__gt__'
>>> (9e9).__lt__(foo)
NotImplemented
Solution
But, none of these methods work with function objects while the < and > operators do work. What goes on under the hood that makes this happen?
In default of any other sensible comparison, CPython in the 2.x series compares based on type name. (This is documented as an implementation detail, although there are some interesting exceptions which can only be found in the source.) In the 3.x series this will result in an exception.
The Python spec places some specific constraint on the behaviour in 2.x; comparison by type name is not the only permitted behaviour, and other implementations may do something else. It is not something to be relied on.
Answered By - Marcin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.