How to avoid overflow errors

Eduardo O. Padoan eduardo.padoan at gmail.com
Fri Sep 14 20:43:38 EDT 2007


On 9/14/07, Steven D'Aprano <steve at remove-this-cybersource.com.au> 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


Not totally unrelated, but in Py3k, as it seems, overflows are really
things of the past:


Python 3.0a1 (py3k:58061, Sep  9 2007, 13:18:37)
[GCC 4.1.3 20070831 (prerelease) (Ubuntu 4.1.2-16ubuntu1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class MyInt(int):
...     pass
...
>>> import sys
>>> MyInt(sys.maxint)
2147483647
>>> MyInt(sys.maxint+1)
2147483648


Thanks to your mail, only now I see how important this change
(int/liong unification) really is!


> How do I subclass int and/or long so that my class also auto-converts
> only when needed?

What about just subclassing long - is this not an option?


> Steven.
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
http://www.advogato.org/person/eopadoan/
Bookmarks: http://del.icio.us/edcrypt



More information about the Python-list mailing list