Friday, November 4, 2022

[FIXED] How to create an independent copy of a function in python?

Issue

Is it possible in python to create an un-linked copy of a function? For example, if I have

a = lambda(x): x
b = lambda(x): a(x)+1

I want b(x) to always return x+1, regardless if a(x) is modified not. Currently, if I do

a = lambda(x): x
b = lambda(x): a(x)+1
print a(1.),b(1.)
a = lambda(x): x*0
print a(1.),b(1.)

the output is

1. 2.
0. 1.

Instead of being

1. 2.
0. 2.

as I would like to. Any idea on how to implement this? It seems that using deepcopy does not help for functions. Also keep in mind that a(x) is created externally and I can't change its definition. I've also looked into using this method, but it did not help.


Solution

You could define b like this:

b = lambda x, a=a: a(x)+1

This makes a a parameter of b, and therefore a local variable. You default it to the value of a in the current environment, so b will hold onto that value. You don't need to copy a, just keep its current value, so that if a new value is created, you have the one you wanted.

That said, this sounds like something unusual happening, and if you tell us more about what's going on, there's likely a better answer.



Answered By - Ned Batchelder
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.