By WebNest Studio Engineering Team
Python Tutorial
Scope, Closures and Namespaces
When Python sees a name like total, which variable does it mean — one inside the function, one in an enclosing function, a module-level one, or a built-in? The answer follows the LEGB rule. Understanding scope explains the global and nonlocal keywords, closures (functions that remember variables from where they were created), and the famous UnboundLocalError.
Why it matters
Scope decides which variable a name refers to, and it is the cause of UnboundLocalError, one of the most puzzling errors for newcomers. Closures, which follow from the same rules, are how decorators and callbacks remember values. Understanding the LEGB rule turns these from mysteries into predictable behaviour.
Namespaces and the LEGB Rule
A namespace maps names to objects. Python looks names up in four scopes, in order: Local (inside the current function), Enclosing (outer functions), Global (module level) and Built-in (len, print...). locals() and globals() return the current namespaces as dicts.
global and nonlocal
Assigning to a name inside a function makes it local to that function for the whole function body. To assign to a module-level variable, declare global name; to assign to a variable of an enclosing function, declare nonlocal name. Global state makes code hard to test — prefer passing values in and returning results.
Closures
A closure is an inner function that remembers variables from its enclosing scope even after the outer function has returned. Closures create function factories (make_multiplier(3)), stateful counters without classes, and are the mechanism behind decorators.
Examples
The LEGB lookup order
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print("inner sees:", x)
inner()
print("outer sees:", x)
outer()
print("module sees:", x)
print("built-in len:", len("abc"))
inner sees: local
outer sees: enclosing
module sees: global
built-in len: 3
UnboundLocalError, global and nonlocal
counter = 0
def broken():
counter += 1 # assignment makes counter local -> error
def increment():
global counter
counter += 1
try:
broken()
except UnboundLocalError as e:
print("UnboundLocalError:", e)
increment(); increment()
print("counter:", counter)
def make_counter():
count = 0
def next_value():
nonlocal count
count += 1
return count
return next_value
tick = make_counter()
print(tick(), tick(), tick())
UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value
counter: 2
1 2 3
Closures remember their environment
def make_discount(percent):
def apply(price):
return round(price * (1 - percent / 100), 2)
return apply
festival = make_discount(20)
student = make_discount(50)
print(festival(1000), student(1000))
print(festival.__closure__[0].cell_contents)
def running_average():
values = []
def add(v):
values.append(v)
return sum(values) / len(values)
return add
avg = running_average()
print(avg(10), avg(20), avg(60))
800.0 500.0
20
10.0 15.0 30.0
Common Mistakes
- Reading a global and then assigning to it in the same function without "global", causing UnboundLocalError.
- Using global variables for state that should be passed as arguments or stored in objects.
- Forgetting nonlocal when updating an enclosing variable from an inner function.
- Shadowing built-ins (list, max, id) in a scope and breaking later code.
Exercise
Write make_counter, which returns a function. Each time the returned function is called it returns the next number, starting at 1. Two counters made by separate calls must count independently.
Expected output: 1, 2, 1 (one per line)
def make_counter():
count = 0
def counter():
# TODO: increase count and return it
pass
return counter
first = make_counter()
print(first())
print(first())
second = make_counter()
print(second())
Show hints
- Assigning to
countinsidecounterwould create a new local variable. - Declare
nonlocal countfirst, so the assignment changes the variable of the enclosing function.
Show solution
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
first = make_counter()
print(first())
print(first())
second = make_counter()
print(second())
Quick quiz
1. In which order does Python search for a name?
- A. Global, local, built-in, enclosing
- B. Local, enclosing, global, built-in
- C. Built-in, global, enclosing, local
- D. Local, global, enclosing, built-in
Show answer
B. This is the LEGB rule.
2. A function contains total += 1, where total is a global variable and there is no global declaration. What happens when it runs?
- A. The global is increased
- B. UnboundLocalError is raised
- C. A new global is created
- D. Nothing
Show answer
B. The assignment makes total local to the function, and it is read before it has a value.
3. What is nonlocal used for?
- A. To change a global variable
- B. To import a name
- C. To create a constant
- D. To assign to a variable of an enclosing function
Show answer
D. global refers to the module level; nonlocal refers to the nearest enclosing function.
Interview questions
What is a closure?
Show answer
A closure is a function that remembers variables from the enclosing function in which it was defined, even after that enclosing function has returned. Each call of the outer function creates a separate set of remembered variables. Closures are used to build functions with stored state, such as counters, and are the mechanism behind decorators.
What is the difference between global and nonlocal?
Show answer
Both allow a function to assign to a variable defined outside it. global name makes the name refer to the variable at module level. nonlocal name makes it refer to the variable in the nearest enclosing function, and that variable must already exist. Neither is needed just to read an outer variable, only to assign to it.
Key Points to Remember
- Names resolve in LEGB order: Local, Enclosing, Global, Built-in.
- Assignment inside a function creates a local unless declared global or nonlocal.
- Closures capture enclosing variables and keep them alive.
- Closures enable function factories, stateful callables and decorators.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering