Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue #10 (__eq__ is too rigid) #16

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

suspectpart
Copy link

I guess this fixes the issue, right?

@suspectpart
Copy link
Author

While at it I applied some refactorings of duplicated logic in d481a7c. If you do not want to mix the bugfix with a refactoring I could move it to a seperate PR (or drop it alltogether, if you find it too invasive).

@suspectpart
Copy link
Author

The Python documentation actually enforces to return NotImplemented when comparing to another type is not supported. This way, the runtime will also ask the other Operand what it thinks about this comparison:

>>> class Thing:
...     def __eq__(self, other):
...             print(f"{self} == {other}")
...             return NotImplemented
... 
>>> Thing() == Thing()
<__main__.Thing object at 0x7ff20a877a60> == <__main__.Thing object at 0x7ff20a8abd30>
<__main__.Thing object at 0x7ff20a8abd30> == <__main__.Thing object at 0x7ff20a877a60>
False
>>> Thing() == 1
<__main__.Thing object at 0x7ff20a8abd30> == 1
False
>>> None == Thing()
<__main__.Thing object at 0x7ff20a8abd30> == None
False

You can see how the runtime first asks the left operand, than the right operand about this comparison. As int and NoneType have the same behavior of returning NotImplemented when being compared to our Thing, we get the chance to answer this comparison (if, for example, we wanted Thing to be comparable to a number, even if it is on the right side of a comparison). :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant