Python Scope
Python looks up names in four scopes, from innermost out: Local, Enclosing, Global, Built-in. Remember it as LEGB.
The four scopes
| Scope | Means |
|---|---|
| Local | Inside the current function. |
| Enclosing | The outer function, if nested. |
| Global | The current module. |
| Built-in | Names like print, len, str. |
LEGB in action
PYTHON
x = 'global'
def outer():
x = 'enclosing'
def inner():
x = 'local'
print(x) # local
inner()
print(x) # enclosing
outer()
print(x) # global
Writing to outer scopes
By default, assignment creates a local. To write to an outer name, declare it:
PYTHON
counter = 0
def bump():
global counter
counter += 1
bump(); bump()
print(counter) # 2
PYTHON
def counter_factory():
n = 0
def bump():
nonlocal n # write to the enclosing n
n += 1
return n
return bump
c = counter_factory()
print(c(), c(), c()) # 1 2 3
Tip: Heavy reliance on
global is a smell. Prefer passing values in and returning new ones out — easier to test and reason about.Example
Example
x = 'global'
def outer():
x = 'enclosing'
def inner():
nonlocal x
x = 'inner'
inner()
print('outer sees:', x)
outer()
print('module sees:', x)
Try it Yourself »
Exercise
Write to a name in the enclosing function scope with…
counter
Eight letters.
Discussion
Loading…