reading-notes

Python Scope

Scope:

LEGB:

Global:

Trying to update a global variable from within a function:

counter = 0  # A global name
>>> def update_counter():
...     counter = counter + 1  # Fail trying to update counter
...
>>> update_counter()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in update_counter
UnboundLocalError: local variable 'counter' referenced before assignment

Nonlocal:

Don’t be CONFUSED by BIG O notation anymore!