0

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?

Stoner
  • 776
  • 1
  • 8
  • 25
Nick stands with Ukraine
  • 2,634
  • 2
  • 32
  • 39
  • Possible duplicate of [UnboundLocalError with nested function scopes](https://stackoverflow.com/questions/2609518/unboundlocalerror-with-nested-function-scopes) – pppery Sep 02 '19 at 15:33

1 Answers1

1

you need nonlocal instead of global. your num_sum is not a global variable (will not be found in globals()). nonlocal will instruct python not to search for it in the global namespace, but in the nearest namespace. the order is LEGB: Local, Enclosed, Global, Built-in.

hiro protagonist
  • 40,708
  • 13
  • 78
  • 98