0

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?

9
  • 1
    import operator? Commented Apr 13, 2016 at 9:05
  • 1
    import operator and operator.eq? Commented Apr 13, 2016 at 9:05
  • 2
    @Michael because it's not called __eq__ but eq! I'm guessing the __eq__ object is actually the module's equality operator (e.g. to test if operator == my_module). Commented Apr 13, 2016 at 9:18
  • 1
    both __eq__ and eq are in the operator module. __eq__ is the magic method, eq is one of the "non-magic" methods of this particular module because it's the operator module. @Michael use operator.eq if 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 to int() and try to do an addtion. E.g. [int(x) + int(x) for x in "1 2 3". split()] Commented Apr 13, 2016 at 10:26
  • 1
    @jDo I have a different understanding of the doc (eq being only a copy of __eq__ for convenience and in fact operator.__eq__ is operator.eq evaluates to True here). Commented Apr 13, 2016 at 11:40

1 Answer 1

1

Just add import operator and the code is working.

import operator

def cmp(a, b, _cmp):
    return _cmp(a, b)

a = 1
b = 2
print(cmp(a, b, operator.__eq__))

I have renamed the function parameter for clarity.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.