# int/long unification hides bugs

Andrew Dalke adalke at mindspring.com
Thu Oct 28 19:28:05 CEST 2004

```Jeremy Fincher wrote:
> The problem with int/long unification is that there is no simple
> pure-Python alternative for those of us who need a bounded integer
> type.  If our code depended on that raised OverflowError in order to
> ensure that our computations were bounded, we're left high and dry
> with ints and longs unified.  We must either drop down to C and write
> a bounded integer type, or we're stuck with code that no longer works.

What's wrong with the example Number wrapper I posted a couple days
ago to this thread?  Here are the essential parts

class RangedNumber:
def __init__(self, val, low = -sys.maxint-1, high = sys.maxint):
if not (low <= high):
raise ValueError("low(= %r) > high(= %r)" % (low, high))
if not (low <= val <= high):
raise ValueError("value %r not in range %r to %r" %
(val, low, high))
self.val = val
self.low = low
self.high = high
....

def _get_range(self, other):
if isinstance(other, RangedNumber):
low = max(self.low, other.low)
high = min(self.high, other.high)
other_val = other.val
else:
low = self.low
high = self.high
other_val = other

return other_val, low, high

other_val, low, high = self._get_range(other)
x = self.val + other_val
return RangedNumber(x, low, high)

...

and some of the example code

>>> a = RangedNumber(10, 0, 100)
>>> print a
10
>>> a+90
RangedNumber(100, 0, 100)
>>> a+91
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "spam.py", line 39, in __add__
return RangedNumber(x, low, high)
File "spam.py", line 8, in __init__
raise ValueError("value %r not in range %r to %r" %
ValueError: value 101 not in range 0 to 100
>>> 10*a
RangedNumber(100, 0, 100)
>>> 11*a
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "spam.py", line 67, in __rmul__
return RangedNumber(x, low, high)
File "spam.py", line 8, in __init__
raise ValueError("value %r not in range %r to %r" %
ValueError: value 110 not in range 0 to 100
>>> b = RangedNumber(18, 5, 30)
>>> a+b
RangedNumber(28, 5, 30)
>>>

Andrew
dalke at dalkescientific.com

```