4

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.

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This works, thanks. I can't see what this is doing though. Care to give explanations\ references?
@YairDaon -- I did explain ... f=c.f gets evaluated when the lambda function is created, not when it is called, so the f that gets passed to the function is c.f (the original).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.