I found that I want to modify a recursive function's behavior for a specific input. I know I can do this by rewriting the function, but as the function could be long I want to avoid duplicating code.
As an example, let's say I have implemented the function lambda x: max(x, 10) in the following recursive way:
def orig_fun(x):
if x < 10:
return orig_fun(x + 1)
return x
but now I want to return 20 whenever the input is 5, as in the following
def desired_fun(x):
if x == 5:
return 20
if x < 10:
return orig_fun(x + 1)
return x
which is the same as adding an if statement in the begging of orig_fun or writing a new function copying the body of orig_fun. I don't want to do this because the body must be many many lines. Of course, doing new_fun = lambda x: 20 if x == 5 else orig_fun(x) does not work because new_fun(3) would be 3 instead of 20.
Is there a way I can solve this in Python3?
note that this is a duplicate of Extend recursive (library) function without code duplication which has no satisfying answer (some user talked about "hacky ways" not presented)
new_fun = lambda x: 20 if x == 5 else orig_fun(x)does not work because new_fun(3) would be 3 instead of 20." I don't understand that sentence.new_fun(3)would be 10 as expected, not 3 and not 20.