3

I have two functions

def greet():
    return 'Hi'

def fun():
    return 'Hello'

When I compare I get fun == greet --> I get false But when I compare them using fun.__eq__(greet) I am getting NotImplemented. Is '==' not same as 'eq'?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Vinay Emmaadii
  • 125
  • 1
  • 11
  • IIRC, when calling python's `==`, it first checks for an internal `__eq__` method, and if it is not implemented, it defaults to its own equality check for objects. Calling the `__eq__` method directly raises the error because you have not implemented this method for `fun` – JacobIRR Dec 09 '18 at 19:59
  • See https://stackoverflow.com/a/879005/2285236 – ayhan Dec 09 '18 at 20:00
  • it's more complex than that; there is a `__eq__` method for functions, but it returns `NotImplemented`. You have to override it. – Jean-François Fabre Dec 09 '18 at 20:01
  • extract of the accepted answer of the dupe link: ""NotImplemented signals to the runtime that it should ask someone else to satisfy the operation. In the expression a == b, if a.__eq__(b) returns NotImplemented, then Python tries b.__eq__(a). If b knows enough to return True or False, then the expression can succeed. If it doesn't, then the runtime will fall back to the built-in behavior (which is based on identity for == and !=)" – Jean-François Fabre Dec 09 '18 at 20:03
  • 1
    notice something tricky: f = lambda x: 4. f.__eq__ = lambda y: True. f == 4 # false. f.__eq__(100) # True. – Aaron_ab Dec 09 '18 at 20:08
  • @Jean-FrançoisFabre Why do I need to overwrite? fun == greet is doing the same in the background and it works. my question is why it does not work with __eq__ which is same as == – Vinay Emmaadii Dec 09 '18 at 20:13
  • 1
    from the link: since `__eq__` returns the NotImplemented singleton, python default `==` behaviour is identity test (`is` operator). I don't think we need to reopen that question. – Jean-François Fabre Dec 09 '18 at 20:15
  • @Jean-FrançoisFabre makes sense. Thanks a ton! – Vinay Emmaadii Dec 09 '18 at 20:21
  • 1
    you're welcome. Note that your question was well-recieved even if a duplicate, and will probably remain in the base. I'm certainly not going to delete it – Jean-François Fabre Dec 09 '18 at 20:24

0 Answers0