python copy function by reference
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