-1

Testing global vars scope,I found with this situation, and can't understand why first function works and sencond don't:
- the error UnboundLocalError is raised at same line -

_D = {'a': 1}

def read():
    print(_D['a'])

def show_and_update():
    print(_D['a'])
    _D = {'a': 1}

read()
> 1

show_and_update()
Traceback (most recent call last):
  File "/home/anybody/.local/share/virtualenvs/nsite-scoli-meter-cx__qsm9/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3441, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-58-a57000dda288>", line 1, in <module>
    show_and_update()
  File "<ipython-input-56-875e227c8e57>", line 2, in show_and_update
    print(_D['a'])
UnboundLocalError: local variable '_D' referenced before assignment
  • 1
    The first function works because it only _reads_ the global variable. The second function does not work because it _assigns_ to the variable, and therefore it is treated as local. Now you might say that it should still work because the assignment happens _after_ the read -- but there's a bit of magic going on here. If there is an assignment to a variable _anywhere_ in the function, then it is treated as a local variable for the _entire_ function, even if the assignment comes later. – John Gordon Mar 08 '22 at 16:20

1 Answers1

3

The second one doesn't work because you create a local variable by having an = assignment. Python sees that you are, recognizes that it should be a new local variable, so it has no initial value at the start; it needs to be assigned a value first. It's just a thing that Python does.

If you want to modify a global variable, put global variable_name at the top of the function

def show_and_update():
    global _D
    print(_D['a'])
    _D = {'a': 1}
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34