In Python, I have an expensive function a(x) which is currently evaluated multiple times within another function. At the start of that function, I want to evaluate a(x) once, and reassign the variable name a locally to that value. But I keep getting an Unbound Local Error.
As a MWE:
def a(x):
return x+1
def main(x):
a = a(x)
return a**2
main(3)
#---------------------------------------------------------------------------
#UnboundLocalError Traceback (most recent call last)
#Input In [62], in <cell line: 8>()
# 5 a = a(x)
# 6 return a**2
#----> 8 main(3)
#
#Input In [62], in main(x)
# 4 def main(x):
#----> 5 a = a(x)
# 6 return a**2
#UnboundLocalError: local variable 'a' referenced before assignment
Obviously, a workaround is to use a line like b = a(x) instead.
But why is this happening? And how can I reassign the variable name a?