Given the following minimal snippet of code:
def cmp(a, b, cmp):
return cmp(a, b)
a = 1
b = 2
print(cmp(a, b, operator.__eq__))
I'd just like to give a built-in operator like == or > as a function handle into a function. This would be useful for example, if comparisons all need some pre-checks.
The last line gives an error, as it does not know operator.__eq__. How do I correctly name (and import) that == operator on that line?
import operator?import operatorandoperator.eq?__eq__buteq! I'm guessing the__eq__object is actually the module's equality operator (e.g. to test ifoperator == my_module).__eq__andeqare in theoperatormodule.__eq__is the magic method,eqis one of the "non-magic" methods of this particular module because it's theoperatormodule. @Michael useoperator.eqif you can;__eq__determines what==means as (at)acdr mentioned. Magic methods (double underscores) allow you to re-define the language on a more fundamental level. Eg.class int(int): def __add__(self,a): print("your mom!")would give some funky results when you later cast something toint()and try to do an addtion. E.g.[int(x) + int(x) for x in "1 2 3". split()]eqbeing only a copy of__eq__for convenience and in factoperator.__eq__ is operator.eqevaluates toTruehere).