fandyst
fandyst

Reputation: 2830

How does the Python interpreter convert an int to a long?

What exactly happens when an int is converted to a long?

For example:

a = sys.maxint-1
a = a+2

What happened in the statement of a = a + 2?

How does the Python interpreter handle the overflow ?

Upvotes: 3

Views: 639

Answers (2)

mgilson
mgilson

Reputation: 310069

Lets read the source (I have python2.7.3 on my machine):

Here's where the addition takes place (as far as I can tell):

static PyObject *
int_add(PyIntObject *v, PyIntObject *w)
{
    register long a, b, x;
    CONVERT_TO_LONG(v, a);
    CONVERT_TO_LONG(w, b);
    /* casts in the line below avoid undefined behaviour on overflow */
    x = (long)((unsigned long)a + b);
    if ((x^a) >= 0 || (x^b) >= 0)
        return PyInt_FromLong(x);
    return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w);
}

So far, not too bad -- We get C long types from the python integer types in the CONVERT_TO_LONG macro. Then they do an addition. Notice how they pull some interesting tricks with casting the various longs in order to detect overflow.* If no overflow is detected, they convert the C long back into a python object and return it. If there is an overflow, you can see that they then try the addition again -- This time, using the python long type (PyLong_Type).

If you look at int_sub, you'll see that it's pretty much the same thing (with slightly different bit trickery to detect underflow). int_mul appears to be a little more complicated, and comes with a nice big block comment. Really, the code is littered with comments about how they deal with the overflow/underflow in different situations. It's pretty informative.

  • I'm a bit too tired right now to unravel it, but if you do, feel free to leave a comment (or just edit).

Upvotes: 4

user1786283
user1786283

Reputation:

First,

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.

Based on question here, How does Python manage int and long?

Also, there is no longer a limit on integers according to http://docs.python.org/3.1/whatsnew/3.0.html

The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).

Basically:

Python seamlessly converts a number that becomes too large for an integer to a long.

Docs here

Upvotes: 3

Related Questions