For numerical comparisons, +- float("inf")
should work.
It doesn’t always work (but covers the realistic cases):
print(list(sorted([float("nan"), float("inf"), float("-inf"), float("nan"), float("nan")])))
# NaNs sort above and below +-Inf
# However, sorting a container with NaNs makes little sense, so not a real issue.
To have objects that compare as higher or lower to any other arbitrary objects (including inf
, but excluding other cheaters like below), you can create classes that state their max/min-ness in their special methods for comparisons:
class _max:
def __lt__(self, other): return False
def __gt__(self, other): return True
class _min:
def __lt__(self, other): return True
def __gt__(self, other): return False
MAX, MIN = _max(), _min()
print(list(sorted([float("nan"), MAX, float('inf'), MIN, float('-inf'), 0,float("nan")])))
# [<__main__._min object at 0xb756298c>, nan, -inf, 0, inf, nan, <__main__._max object at 0xb756296c>]
Of course, it takes more effort to cover the ‘or equal’ variants. And it will not solve the general problem of being unable to sort a list containing None
s and int
s, but that too should be possible with a little wrapping and/or decorate-sort-undecorate magic (e.g. sorting a list of tuples of (typename, value)
).