Consider the following code snippet (Note I was using global because nonlocal keywords is not available in Python 2.7)
def foo(L,K):
global count
count = 0
def bar(f,L):
global count
for e in L:
if e - f == K or f - e == K: count += 1
yield e
try:
while True:
L = bar(L.next(),L)
except StopIteration:
return count
count=0
print foo((int(e) for e in some_string.split()),some_number)
where
some_string: A space delimited integers
some_number: An integer
when len(some_string) = 4000, the above code fails with the error
RuntimeError: maximum recursion depth exceeded while calling a Python object
Is it because internally nested generators are implemented as recursion?
You are replacing
L, with the result ofbar, which is a generator itself. Thus, you end up passingbarback tobarin the form of recursively nested generator expressions.This construction eventually passes the recursion depth limits.