Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python compare functions?

Tags:

python

sorting

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

like image 634
pprzemek Avatar asked Oct 29 '11 23:10

pprzemek


People also ask

Does Python have a compare function?

Python - cmp() MethodThe cmp() is part of the python standard library which compares two integers. The result of comparison is -1 if the first integer is smaller than second and 1 if the first integer is greater than the second. If both are equal the result of cmp() is zero.

How do you compare results in Python?

As a basic comparison operator you'll want to use == and != . They work in exactly the same way as with integer and float values. The == operator returns True if there is an exact match, otherwise False will be returned.

How do you compare lists in Python?

Using list.sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.

How do you compare in Python 3?

If values of two operands are not equal, then condition becomes true. (a!= b) is true. If the value of left operand is greater than the value of right operand, then condition becomes true.


1 Answers

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.

like image 69
Raymond Hettinger Avatar answered Sep 28 '22 10:09

Raymond Hettinger