Maximum negative integer string representations are not accepted by int(). Why?

Parzival Herzog parz at shaw.SpamBucket.ca
Fri Feb 21 23:26:18 EST 2003


If I can write:

>>> int(-2147483648)
-2147483648

or
>>> int(-2147483648.0)
-2147483648
>>>

or
>>> int(020000000000)
-2147483648

Then, why can I not write:

>>> int("020000000000")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: int() literal too large: 020000000000

or

>>> int("020000000000", 8)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: int() literal too large: 020000000000
>>>

or

>>> int("ffffffff",16)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: int() literal too large: ffffffff
>>>

?

The maximum negative integer is perfectly legal value of the integer
type, so what is the rationale/justification for the int() function,
rejecting this value, only when the argument is a string, but not when it
is the same value in some other non-integer type?

Or is this a bug?

What do you suggest as a way to extend the range of int() to include
strings representing the maximum negative integer ? Its obvious that
explicit base conversion will do the trick:

>>> int(-reduce(lambda x,y: x*8+int(y),"20000000000",0))
-2147483648
>>>

but I am fishing for something less brutal than that.
(You might as well exclude using int() to convert strings in
that case.)


- Parzival








More information about the Python-list mailing list