views:

363

answers:

4

Does anybody know how Python manage internally int and long types?

  • Does it choose the right type dynamically?
  • What is the limit for an int?
  • I am using Python 2.6, Is is different with previous versions?

How should I understand the code below?

>>> print type(65535)
<type 'int'>
>>> print type(65536)
<type 'int'>
>>> print type(65535*65535)
<type 'long'>
>>> print type(65536*65536)
<type 'long'>

Update:

>>> print type(0x7fffffff)
<type 'int'>
>>> print type(0x80000000)
<type 'long'>
+2  A: 

int and long were "unified" a few versions back. Before that it was possible to overflow an int through math ops.

3.x has further advanced this by eliminating int altogether and only having long.

sys.maxint contains the maximum value a Python int can hold.

Ignacio Vazquez-Abrams
But Python3 calls this type 'int', even though it behaves more like 2.x's 'long'.
Roger Pate
+3  A: 

This PEP should help.

Bottom line is that you really shouldn't have to worry about it in python versions > 2.4

mluebke
+2  A: 

On my machine:

>>> print type(1<<30)
<type 'int'>
>>> print type(1<<31)
<type 'long'>
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'long'>

Python uses ints (32 bit signed integers, I don't know if they are C ints under the hood or not) for values that fit into 32 bit, but automatically switches to longs (arbitrarily large number of bits - i.e. bignums) for anything larger. I'm guessing this speeds things up for smaller values while avoiding any overflows with a seamless transition to bignums.

MAK
A: 

It manages them because int and long are sibling class definitions. They have appropriate methods for +, -, *, /, etc., that will produce results of the appropriate class.

For example

>>> a=1<<30
>>> type(a)
<type 'int'>
>>> b=a*2
>>> type(b)
<type 'long'>

In this case, the class int has a __mul__ method (the one that implements *) which creates a long result when required.

S.Lott