Tes*_*act 26 python recursion cpython python-internals
当通过解包参数调用函数时,它似乎会增加两次递归深度.我想知道为什么会这样.
一般:
depth = 0
def f():
    global depth
    depth += 1
    f()
try:
    f()
except RuntimeError:
    print(depth)
#>>> 999
通过拆包电话:
depth = 0
def f():
    global depth
    depth += 1
    f(*())
try:
    f()
except RuntimeError:
    print(depth)
#>>> 500
理论上两者都应达到1000左右:
import sys
sys.getrecursionlimit()
#>>> 1000
这发生在CPython 2.7和CPython 3.3上.
在PyPy 2.7和PyPy 3.3上存在差异,但它要小得多(1480 vs 1395和1526 vs 1395).
从反汇编中可以看出,除了调用类型(CALL_FUNCTIONvs CALL_FUNCTION_VAR)之外,两者之间几乎没有区别:
import dis
def f():
    f()
dis.dis(f)
#>>>  34           0 LOAD_GLOBAL              0 (f)
#>>>               3 CALL_FUNCTION            0 (0 positional, 0 keyword pair)
#>>>               6 POP_TOP
#>>>               7 LOAD_CONST               0 (None)
#>>>              10 RETURN_VALUE
def f():
    f(*())
dis.dis(f)
#>>>  47           0 LOAD_GLOBAL              0 (f)
#>>>               3 BUILD_TUPLE              0
#>>>               6 CALL_FUNCTION_VAR        0 (0 positional, 0 keyword pair)
#>>>               9 POP_TOP
#>>>              10 LOAD_CONST               0 (None)
#>>>              13 RETURN_VALUE
Mar*_*ers 18
异常消息实际上为您提供了提示.比较非解包选项:
>>> import sys
>>> sys.setrecursionlimit(4)  # to get there faster
>>> def f(): f()
... 
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
RuntimeError: maximum recursion depth exceeded
有:
>>> def f(): f(*())
... 
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
RuntimeError: maximum recursion depth exceeded while calling a Python object
注意添加了while calling a Python object.此异常特定于该PyObject_CallObject()功能.设置奇数递归限制时,您不会看到此异常:
>>> sys.setrecursionlimit(5)
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
RuntimeError: maximum recursion depth exceeded
因为这是在提出的具体的异常ceval.c帧估计代码里面PyEval_EvalFrameEx():
/* push frame */
if (Py_EnterRecursiveCall(""))
    return NULL;
注意那里的空信息.这是一个至关重要的区别.
对于'常规'函数(没有变量参数),会发生的是选择优化路径 ; 不需要元组或关键字参数解包支持的Python函数直接在评估循环的fast_function()函数中处理.创建并运行具有该函数的Python字节码对象的新frameobject.这是一次递归检查.
但是对于带有变量参数的函数调用(元组或字典或两者),fast_function()不能使用该调用.相反,使用ext_do_call()(扩展调用),它处理参数解包,然后用于PyObject_Call()调用函数.PyObject_Call()执行递归限制检查,并"调用"函数对象.函数对象是通过function_call()函数调用的,该函数调用PyEval_EvalCodeEx()哪个函数PyEval_EvalFrameEx()进行第二次递归限制检查.
除非进行参数解包PyObject_Call(),否则调用Python函数的Python函数将被优化并绕过C-API函数.Python帧执行和PyObject_Call()make递归限制测试,所以绕过PyObject_Call()避免增加每次调用的递归限制检查.
您可以Py_EnterRecursiveCall为其他进行递归深度检查的位置grep Python源代码; 例如,各种库,例如json,pickle使用它来避免解析嵌套太深或递归的结构.其他检查被放置在list和tuple __repr__实施方式中,富比较(__gt__,__lt__,__eq__等),处理__call__可调用对象钩和处理__str__呼叫.
因此,您可以更快地达到递归限制:
>>> class C:
...     def __str__(self):
...         global depth
...         depth += 1
...         return self()
...     def __call__(self):
...         global depth
...         depth += 1
...         return str(self)
... 
>>> depth = 0
>>> sys.setrecursionlimit(10)
>>> C()()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in __call__
  File "<stdin>", line 5, in __str__
RuntimeError: maximum recursion depth exceeded while calling a Python object
>>> depth
2