How Python Implements "long integer"?

Mark Dickinson dickinsm at gmail.com
Sun Jul 5 09:04:11 EDT 2009


On Jul 5, 1:09 pm, Pedram <pm567... at gmail.com> wrote:
> Thanks for reply,
> Sorry I can't explain too clear! I'm not English ;)

That's shocking.  Everyone should be English. :-)

> But I want to understand the implementation of long int object in
> Python. How Python allocates memory and how it implements operations
> for this object?

I'd pick one operation (e.g., addition), and trace through the
relevant functions in longobject.c.  Look at the long_as_number
table to see where to get started.

In the case of addition, that table shows that the nb_add slot is
given by long_add.  long_add does any necessary type conversions
(CONVERT_BINOP) and then calls either x_sub or x_add to do the real
work.
x_add calls _PyLong_New to allocate space for a new PyLongObject, then
does the usual digit-by-digit-with-carry addition.  Finally, it
normalizes
the result (removes any unnecessary zeros) and returns.

As far as memory allocation goes: almost all operations call
_PyLong_New at some point.  (Except in py3k, where it's a bit more
complicated because small integers are cached.)

If you have more specific questions I'll have a go at answering them.

Mark



More information about the Python-list mailing list