Tuesday, September 13, 2011

Python automatic int to long conversion

The language says that if a value fits within an int, it should be an int, otherwise, it is automatically promoted to a long.


Let's take a look at these examples on a 32-bit CPython, these could make great interview questions ;):

>>> type(2**31)
<type 'long'>
>>> type(-2**31)
<type 'long'>
>>> type((-2)**31)
<type 'int'>
>>>

The first value is obviously off. Two to the power of thirty-one is one greater than what could be presented by an int. The second one seems to be an int at first, but operator precedence requires power to be evaluated first so we got a minus of a long which should be a long. The final value is within bound.

Just a side note, I wanted to have the minimum 32-bit integer value without using sys.maxint (because it may be different on 64-bit interpreter) while working on hsalf. And these were the experiments ;).

No comments:

Post a Comment