How does python compare functions?

How come this doesn’t rise Attribute error? function object doesn’t have any of the comparison methods. Does it use id() somehow?

fun1 = lambda:x
fun2 = lambda:x
print fun1 == fun1 # True
print fun1 == fun2 # False
print fun1 > fun2 # True
print fun1 < fun2 # False
print fun1 > 1 # True

I understand that it compares addresses, but how?
Is it some low level hack in to intercept __lt__, __eq__ etc. ?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Function objects do not define their own comparisons or rich comparisons. Instead, they inherit from type objects which implement rich comparisons based on the object’s address in memory.

So yes, it effectively uses addresses just like the built-in id() function does.

In Python 3, functions are no longer orderable.

Method 2

__eq__, __lt__ et al. don’t implement comparisons in Python, they just let you override it.

The Python language reference states:

Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.

It’s possible this is done by comparing object ids but this isn’t specified by the language.

I’m not sure what the rationale is behind making any object comparable to any other object, but it’s a built-in feature of the language – the reference does mention it makes any list sortable, which makes the definition of comparing two dictionaries easier.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x