vimeo / py-money

Money class for Python 3
MIT License
125 stars 27 forks source link

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

Open suspectpart opened 3 years ago

suspectpart commented 3 years ago

I guess this fixes the issue, right?

suspectpart commented 3 years ago

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 commented 3 years ago

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). :-)