0

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?

1
  • "copy by reference" is not really standard terminology. You should really explain what you mean more explicitly. Note, there is no copying going on anywhere in your code. Python assignment never copies. You should read: nedbatchelder.com/text/names.html Commented Jan 12, 2022 at 8:54

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

it's exactly what i want for! Thanks a lot.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.