Rich comparisons of Timestamps raise TypeError instead of returning NotImplemented #24011
The problem is that pandas'
The current behaviour prevents other objects to deal with comparisons with
# Let's define infinity, or any object whose magic methods support Timestamp class Inf: def __lt__(self, o): return False def __le__(self, o): return isinstance(o, Inf) def __gt__(self, o): return not isinstance(o, Inf) def __ge__(self, o): return True def __eq__(self, o): return isinstance(o, Inf) def __ne__(self, o): return not self == o # Required for Python 2 def __repr__(self): return '+inf' # Import pandas and create a timestamp import pandas as pd timestamp = pd.Timestamp('2018-11-30') # Comparison works if compared in *that* order, because magic method is called on Inf assert Inf() > timestamp assert not (Inf() < timestamp) # ... but not when magic method is called on Timestamp assert timestamp < Inf()
... raises the following:
@jbrockmendel Support for Python 2 will be dropped at the end of the year if I'm right. It's not a big deal (at least to me) to wait until 2019 to see this behaviour "fixed" ;-)
@TomAugspurger I can give it a try, but I'm not used to Cython nor to deploy/test libraries with C-extensions. I'll keep you informed of my progress on this.
With a clean installation of current master branch, two tests errored:
I made the change to return
However, I don't know if I have to do something specific after having changed the code (e.g. building pandas again or something else) ?
No, I didn't. I'm not used to "compile" Python code ;-)
Here are the results of
The one that failed is
Notice that I simply added
if op == Py_EQ: return False elif op == Py_NE: return True raise TypeError('Cannot compare type %r with type %r' % (type(self).__name__, type(other).__name__))
With this change, the piece of code I provided in the first post passes.
I created a PR to get test results from CI. Some of the failing tests are (depending on the chosen build process):