0

I was not able to find anything useful in the documentation for Python 3.6. However, the docs for 3.10 state:

By default, object implements __eq__() by using is, returning NotImplemented in the case of a false comparison: True if x is y else NotImplemented.

This seems to be right for Python 3.6 as well.

class Foo():
    pass

print(Foo().__eq__(Foo())) # prints NotImplemented

However, I don't understand why

print(Foo() == Foo()) # prints False

prints not NotImplemented, but False. What is == doing here?

khelwood
  • 55,782
  • 14
  • 81
  • 108
zwithouta
  • 1,319
  • 1
  • 9
  • 22

1 Answers1

2

When __eq__ is not defined Python computes object.__eq__(a, b) which returns True if and only if they are the same object.

See https://stackoverflow.com/a/63310298/3275464 for more details.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Learning is a mess
  • 7,479
  • 7
  • 35
  • 71
  • `object.__eq__(Foo(), Foo())` is _also_ `NotImplemented`, not `False`. – jonrsharpe Jan 12 '22 at 16:56
  • 1
    The key thing to understand is that `a == b` is not equal to `__eq__(a, b)`, but that it is equal to a function that calls `__eq__` and - given `__eq__(a, b)` returns `NotImplemented` - returns `a is b`. This is explained in the answer linked above: https://stackoverflow.com/a/42592404/10680954 – zwithouta Jan 12 '22 at 20:22
  • @zwithouta Indeed you are correct, I glossed over this important detail, the link I shared does contain this info still ;) – Learning is a mess Jan 13 '22 at 16:56