[Tutor] multiple assignments when reading a file

eryksun eryksun at gmail.com
Thu Jul 11 15:53:14 CEST 2013


On Thu, Jul 11, 2013 at 1:15 AM, Dave Angel <davea at davea.name> wrote:
> There might even be a limit of how many locals a function may have, but I
> don't know what it is.  Probably at least 256.

Going by just the stack and opcode limits, one could potentially
unpack into over 2 billion local variables in CPython. In practice,
that's ridiculous and you'd hit other limits trying to compile it.

A quick check unpacking into a million local variables did work, so
for all practical purposes running out of space for locals is nothing
to worry about.

    f_template = r'''
    def f():
        %s = xrange(%d)'''

    def make_f(n):
        a = ','.join('a%d' % i for i in xrange(n))
        return f_template % (a, n)

    >>> exec make_f(1000000)
    >>> f.__code__.co_stacksize
    1000000

Whatever you do, don't dis() that function. It has a million STORE_FAST ops.

I did unpacking here to show that UNPACK_SEQUENCE(count) can be
extended to a double-word by a preceding EXTENDED_ARG op. In other
words the count can be larger than 65535 in CPython. This was added in
2.0 beta 1:

    The limits on the size of expressions and file in Python source
    code have been raised from 2**16 to 2**32. Previous versions of
    Python were limited because the maximum argument size the
    Python VM accepted was 2**16. This limited the size of object
    constructor expressions, e.g. [1,2,3] or {'a':1, 'b':2}, and
    the size of source files. This limit was raised thanks to a
    patch by Charles Waldman that effectively fixes the problem. It
    is now much more likely that you will be limited by available
    memory than by an arbitrary limit in Python.


More information about the Tutor mailing list