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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With