안유빈
안유빈

Reputation: 43

python copy function by reference

My question is about function callback to be copied by reference

func1 = lambda a, b : a+b
func2 = lambda a, b : a*b
ref = func1
ref_ref = ref
ref = func2
print(ref_ref(3,5)) # it returns 8, not 15

I wanted to call function with copy by reference(so that the result returns 15) but it didn't work.

How can I get this?

Upvotes: 0

Views: 55

Answers (1)

Jakob Stark
Jakob Stark

Reputation: 3845

From your variable naming, it is kind of obvious what you expected, but thats not the way assignment works in python. After the assignment to ref_ref all the variables func1, ref and ref_ref are actually completely equivalent. ref_ref is not a reference to ref but directly refers to the same function object, that also func1 and ref refer to. There is no kind of recursive reference involved here.

If you want to achieve the functionality that you expected in your code, you actually need an object, that can lazily resolves a variably name. So you could do

func1 = lambda a, b : a+b
func2 = lambda a, b : a*b
ref = func1
ref_ref = lambda : ref
ref = func2
print(ref_ref()(3,5)) # it returns 15

Upvotes: 1

Related Questions