How to avoid overflow errors

James Stroud jstroud at mbi.ucla.edu
Fri Sep 14 21:19:45 EDT 2007


Steven D'Aprano wrote:
> I thought that overflow errors would be a thing of the past now that 
> Python automatically converts ints to longs as needed. Unfortunately, 
> that is not the case.
> 
>>>> class MyInt(int):
> ...     pass
> ...
>>>> MyInt(sys.maxint)
> 2147483647
>>>> MyInt(sys.maxint+1)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> OverflowError: long int too large to convert to int
> 
> 
> How do I subclass int and/or long so that my class also auto-converts 
> only when needed?
> 
> 
> 

Use __new__.

py> import sys
py>
py> class MyLong(long):
...   pass
...
py> class MyInt(int):
...   def __new__(cls, *args, **kwargs):
...     try:
...       return int.__new__(cls, *args, **kwargs)
...     except OverflowError:
...       return MyLong(*args, **kwargs)
...
py> MyInt(sys.maxint**2)
4611686014132420609L
py> type(_)
<class '__main__.MyLong'>


James



More information about the Python-list mailing list