You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CPython实现的Python函数最多可支持多少个局部变量?

Testing Python's Maximum Local Variable Limit in Functions

We all know Python dumped the old 255 explicit argument limit back in 3.7—now the only constraint is your system's sys.maxsize from container limits. But what about local variables inside functions?

First, let's clear up why hacky dynamic approaches don't work:

  • You can't just slap new local variables into a function on the fly, and messing with locals() won't let you actually access those variables directly in the function code.
  • Even if you use exec or compile to stuff entries into locals(), this doesn't update the function's __code__.co_varnames tuple. That tuple is what Python uses to map local variable names to their storage slots at runtime, so those dynamically added names are invisible to the interpreter when you try to reference them explicitly.

Take this example:

def bar():
    exec('k=10')
    print(f"locals: {locals()}")
    print(k)
    g = 100

bar()

Running this gives you:

locals: {'k': 10}
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-143-226d01f48125> in <module>()
----> 1 bar()

<ipython-input-142-69d0ec0a7b24> in bar()
      2     exec('k=10')
      3     print(f"locals: {locals()}")
----> 4     print(k)
      5     g = 100
      6

NameError: name 'k' is not defined

And checking the function's code object shows only g is registered as a local:

bar.__code__.co_varnames
# Output: ('g',)

Even if you loop to create 131072 variables via exec:

for i in range(2**17):
    exec(f'var_{i} = {i}')

Your locals() dict will be stuffed full, but trying to print(var_100) will still throw a NameError—Python doesn't see those as real local variables.

Of course, in real code, you'd never do this; a dictionary or custom namespace object is the way to go for dynamic collections of values. But if you want to properly test the hard limit for local variables, here's how:

How to Test the Real Limit

Python's bytecode uses LOAD_FAST and STORE_FAST instructions for local variables, which rely on 16-bit indices. That means the theoretical maximum number of local variables a function can have is 65535 (2^16 - 1).

To verify this, you need to generate a function with explicit local variables (not dynamically added) — because only explicit declarations get added to co_varnames and use those fast storage slots.

Here's a script to test this:

import sys

def make_func_with_n_locals(n):
    # Generate code that defines n local variables
    var_lines = "\n    ".join([f"var_{i} = {i}" for i in range(n)])
    # Reference all variables to ensure they're treated as locals (not discarded by the interpreter)
    ref_lines = "\n    ".join([f"var_{i}" for i in range(n)])
    func_source = f"""
def test_func():
    {var_lines}
    {ref_lines}
"""
    # Execute the code to define the function in our global scope
    exec(func_source, globals())
    return test_func

# Test the theoretical maximum
try:
    test_func = make_func_with_n_locals(65535)
    test_func()
    print("Success! Created a function with 65535 local variables.")
except Exception as e:
    print(f"Failed with 65535 variables: {str(e)}")

# Test one over the limit to confirm the error
try:
    test_func = make_func_with_n_locals(65536)
    test_func()
except Exception as e:
    print(f"As expected, failed with 65536 variables: {str(e)}")

When you run this, you'll see that 65535 works fine, but 65536 throws a SyntaxError: too many local variables. That's because the 16-bit index can't go beyond 65535—Python can't generate valid bytecode for more local variables than that.


内容的提问来源于stack exchange,提问作者Kasravnd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:34:19