Jiaji Huang
Jiaji Huang

Reputation: 331

Update a lambda function iteratively in a loop

I want to update a python lambda function for several times, e.g.,

f = lambda x: 0
for t in range(10):
    g_t = .... # some function independent of f
    f = lambda x: f(x) + g_t(x) # update f for 10 times

calling f gives me:

...

File "<stdin>", line 3, in <lambda>

File "<stdin>", line 3, in <lambda>

...

File "<stdin>", line 3, in <lambda>

RuntimeError: maximum recursion depth exceeded

Anyway to get around this?

Upvotes: 0

Views: 1293

Answers (1)

user1726343
user1726343

Reputation:

If you invoke f after the snippet you've pasted, you'll get unbounded recursion, and will eventually exceed the maximum stack depth.

This is because Python closures are captured lexically, meaning they point at the variable name in scope, not the specific value of the variable at the point in time when the lambda is created. When the final value of f is invoked, the f(x) expression will recursively invoke the final value of f, not the value from the previous iteration.

The workaround is to pass the current value of f as an argument to the new lambda you are creating, instead of closing over it:

f = lambda x: 0
for t in range(10):
    g_t = lambda x: 1 # some function independent of f
    f = lambda x, curr_f=f: curr_f(x) + g_t(x) # pass f as a default argument to the lambda
print(f(0)) # prints 10, no stack overflow

Upvotes: 4

Related Questions