Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite recursion using lambda in python

I have a class. This class contains a function. I want to change this function in the same way every once in a while. If I use lambda I get infinite recursion. I understand why I get this, I want to find an elegant solution.

def func(s):
    return  1 # some not interesting function

class cls: # a class

    def __init__(self , f):
    self.f = f

c = cls(func)
c.f = lambda x: c.f(x) + 1 #  i want c.f to return c.f(x) + 1
print(c.f(1)) # causes infinite recursion

I don't want to do

c.f = lambda x: func(x) + 1 

because I want to change c.f in the same way more than once.

like image 251
Yair Daon Avatar asked Oct 16 '25 17:10

Yair Daon


1 Answers

The infinite recursion is happening because inside the lambda function, c.f is resolved at call-time, so it's already the "new" lambda function instead of the original function passed to cls.__init__.

You could do something like this:

c.f = lambda x, f=c.f: f(x) + 1

Since the argument default is evaluated at the time the lambda function is created, it will be the original function on the class.

like image 190
mgilson Avatar answered Oct 18 '25 06:10

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!