iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Scope

Python looks up names in four scopes, from innermost out: Local, Enclosing, Global, Built-in. Remember it as LEGB.

The four scopes

ScopeMeans
LocalInside the current function.
EnclosingThe outer function, if nested.
GlobalThe current module.
Built-inNames 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

Test yourself

Q1. The LEGB order is…
Q2. To write to the enclosing function scope, use…
Q3. To write to a module-level name, use…

Discussion

Loading…