I’m working on a library that implements a data structure that works with any ordered data type–a rangeset. Many of the operations (like inversion) get interesting when you allow for positive and negative infinity.
One goal is to get datetime objects to work with this module, and in supporting infinity with non-numeric objects, I’ve created INFINITY and NEGATIVE_INFINITY:
class _Indeterminate(object):
def __eq__(self, other):
return other is self
@functools.total_ordering
class _Infinity(_Indeterminate):
def __lt__(self, other):
return False
def __gt__(self, other):
return True
def __str__(self):
return 'inf'
__repr__ = __str__
@functools.total_ordering
class _NegativeInfinity(_Indeterminate):
def __lt__(self, other):
return True
def __gt__(self, other):
return False
def __str__(self):
return '-inf'
INFINITY = _Infinity()
NEGATIVE_INFINITY = _NegativeInfinity()
Unfortunately, this doesn’t work for datetime objects when on the left hand side of the cmp() operation:
In [1]: from rangeset import *
In [2]: from datetime import datetime
In [3]: now = datetime.now()
In [4]: cmp(INFINITY, now)
Out[4]: 1
In [5]: cmp(now, INFINITY)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/axiak/Documents/rangeset/<ipython-input-5-c928d3687d92> in <module>()
----> 1 cmp(now, INFINITY)
TypeError: can't compare datetime.datetime to _Infinity
I had hoped I could get around this limitation by using a cmp wrapper that just ensures that my objects are always called, but I really want to use the .sort() method which will cause cmp to be called between these objects.
Is there any way to create an object which is truly less than any other object, and truly greater than any other object?
Module home: https://github.com/axiak/py-rangeset
from the docs
so to allow comparison with datetime objects add a
timetuplemethod e.g.output: