|
|
|
|
|
by JulianChastain
745 days ago
|
|
Yes, I believe that this is due to how python lets you dynamically redefine functions even to violate lexical scoping. So in the author's example: def f(x):
if x > 0:
return f(x-1)
return 0
# Here is where a compiler might assume that f(x) is tail recursive, and so do TCE
g = f
def f(x):
return x
g(5)
So according to the python standard, g(5) returns 4, since it calls the original f, but then the first recursive call will go to the new f. If f was TCE'd, then it would return 0, as the actual recursion would be eliminated, so it wouldn't matter that you've reassigned f to a new function. |
|
Incidentally: I don't believe that is a violation of lexical scoping. f is scoped globally, inside itself f is not defined, so f(x-1) refers to the globally scoped f. When it's reassigned, you reassign the global f. Nothing here violates lexical scoping, since f is never scoped anywhere other than globally (note that the blog post never claims it is, either)
I don't disagree with Guido's larger point, though, Python probably shouldn't use TCO. The debugging/stack trace point is very true, and also it's just not Pythonic to write algorithms TCO style. You just don't need to, in Python.