max max - 2 months ago 13
Python Question

How to make an integer larger than any other integer?

I need to create an integer that's larger than any other integer. Use case: library function expects an integer, and the only easy way to force a certain behavior is to pass a very large integer.

In python 2, I can use

sys.maxint
. In python 3,
float('inf')
is the closest equivalent, but I can't convert it to
int
.

To clarify based on @wim answer,
sys.maxint
is completely irrelevant. It won't even work in python 2.

wim wim
Answer

Since python integers are unbounded, you have to do this with a custom class:

>>> from functools import total_ordering
>>> @total_ordering
... class ReallyMaxInt(int):
...     def __eq__(self, other):
...         return isinstance(other, ReallyMaxInt)
...     def __lt__(self, other):
...         return False
...     def __repr__(self):
...         return 'ReallyMaxInt()'
...     
>>> 
>>> i = ReallyMaxInt()
>>> i > sys.maxint
True
>>> isinstance(i, int)
True

Note that in python2, sys.maxint + 1 is bigger than sys.maxint, so you can't rely on that.