Search code examples
pythonlambdacrashkernelrestart

Kernel restarts when calling self defined function which adds together lambda functions


I've tried to define a function that adds several lambda functions together. When I call the function the kernel crashes and restarts with no further error messages.

def add_lambdas(function_list):
    f = lambda x, y: None
    for function in function_list:
        f = lambda x, y: f(x, y) + function(x, y)
    return f

f1 = lambda x, y: x + y
f2 = lambda x, y: x**2 - 2*y

f3 = lambda x, y: f1(x,y) + f2(x,y)
f4 = add_lambdas([f1,f2])

For example, when I call f3(2,3) all is well, but when I call f4(2,3) the kernel crashes and restarts. For f3 I do the adding of f1 and f2 manually, but for f4 I pass them through the function add_lambdas().

This is the output:

In[5]: f3(2,3)
Out[5]: 3

In[6]: f4(2,3)

Restarting kernel...

Obviously something is wrong with my defined function, but I cant figure out what it is. Any thoughts? Thank you!


Solution

  • I believe the problem is that you're defining f as a recursive function, which I don't think is what you want. You can try this instead:

    def add_lambdas(function_list):
        return lambda x, y: sum(f(x, y) for f in function_list)