I have the following snippet:
def test ():
num_sum = 0
def inner_test ():
global num_sum
num_sum += 1
inner_test()
return num_sum
When I run test() I get:
NameError: name 'num_sum' is not defined
I was expecting that the inner function would change the value of the num_sum
variable defined in the outer function. Basically, I need a global variable to increment in an inner function which I may call recursively.
I noticed that this pattern works well with collections (lists, dictionaries) even if I don't define the variable as global (but pass it as a parameter to the inner function).
However, with scalar values like int
this pattern seems to break. Neither defining the variable as global (as is here) nor passing it as a parameter to the inner function works as intended. Basically, the scalar variable stays unchanged. What do I need to do to get the desired behaviour with such scalar values?