def tail_call_optimized(g): """ This function decorates a function with tail call optimization. It does this by throwing an exception if it is it's own grandparent, and catching such exceptions to fake the tail call optimization. This function fails if the decorated function recurses in a non-tail context. """ def func(*args, **kwargs): f = sys._getframe()
if f.f_back
and f.f_back.f_back \
and f.f_back.f_back.f_code == f.f_code:
raise TailRecurseException(args, kwargs)
else:
while 1:
try:
return g(*args, **kwargs)
except TailRecurseException, e: args = e.args kwargs = e.kwargs func.__doc__ = g.__doc__
return func
@tail_call_optimizeddef factorial(n, acc=1): "calculate a factorial" if n ==
0:
return acc
return factorial(n
-1, n*acc)
print factorial(
10000)
為了更清晰的展示開啟尾遞歸優(yōu)化前、后調用棧的變化和tail_call_optimized裝飾器拋異常退出遞歸調用棧的作用, 我這里利用 pudb調試工具 做了動圖 <br/>
開啟尾遞歸優(yōu)化前的調用棧

5/7 首頁 上一頁 3 4 5 6 7 下一頁 尾頁