Skip to content

Module 9 · Functions — topic 15 of 19

Scope

The LEGB rule (Local, Enclosing, Global, Built-in) for name lookup, nested functions and nonlocal, and how scope keeps programs predictable.

Beginner 12 min read·Lesson 140 of 306 in Python Programming

Learning objectives

  • Apply the LEGB rule to predict which value a name refers to
  • Use nonlocal to rebind a variable of an enclosing function
  • Avoid shadowing built-in names

Definition

Scope is the region of a program where a name is visible. Python resolves names using the LEGB rule: the Local scope, then any Enclosing function scopes, then the Global (module) scope, then Built-in names.

Introduction

When you write x inside a function, which x is it? Python answers with a fixed search order — local first, then outward — called the LEGB rule.

Why it matters

Scope rules explain closures, decorators and many puzzling bugs, such as a variable called list breaking every later call to list().

Detailed explanation

Local: names assigned in the current function. Enclosing: names in any outer function that contains this one. Global: names at the top level of the module. Built-in: names like len, print and list that Python provides.

Lookup stops at the first scope that has the name. That's why a local can hide (shadow) a global or a built-in.

Blocks such as if, for and while don't create scopes in Python: a variable assigned in a loop is still visible after it, in the same function.

A nested function can read variables of its enclosing function. To rebind one, it declares nonlocal name — the enclosing-scope counterpart of global.

Comprehensions and lambdas have their own scope, so a comprehension's loop variable doesn't leak.

Syntax

Python
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # local
inner()
def counter():
count = 0
def step():
nonlocal count # rebind the enclosing variable
count += 1
return count
return step
  • Search order: Local, Enclosing, Global, Built-in.
  • nonlocal rebinds an enclosing function's variable.
  • if/for don't create scopes.

Code examples

LEGB in action

Python
x = "global"
def outer():
x = "enclosing"
def inner():
print("inner sees:", x)
inner()
outer()
print("module sees:", x)
print("built-in len:", len("abc"))
Output
inner sees: enclosing
module sees: global
built-in len: 3

Loops don't create scopes

Python
def last_even(numbers):
for n in numbers:
pass
return n # still visible after the loop
print(last_even([3, 8, 5]))
squares = [i * i for i in range(3)]
try:
print(i)
except NameError:
print("comprehension variable i did not leak")
Output
5
comprehension variable i did not leak

More examples

nonlocal and shadowed built-ins

Python
def make_counter(start=0):
count = start
def step(by=1):
nonlocal count
count += by
return count
return step
clicks = make_counter()
clicks(); clicks()
print(clicks(5))
other = make_counter(100)
print(other(), clicks())
list = [1, 2, 3] # shadows the built-in list!
try:
list("abc")
except TypeError as e:
print("TypeError:", e)
del list # remove the shadowing name
print(list("abc"))
Output
7
101 8
TypeError: 'list' object is not callable
['a', 'b', 'c']

Step-by-step explanation

  • make_counter's count lives in the enclosing scope of step.
  • nonlocal lets step rebind count; each make_counter call creates an independent count.
  • Assigning list = [...] creates a global named list that hides the built-in, so list('abc') tries to call a list.
  • del list removes the global, and lookup falls back to the built-in again.

Expected output

Running “nonlocal and shadowed built-ins” prints exactly:

TextOutput
7
101 8
TypeError: 'list' object is not callable
['a', 'b', 'c']

Practical applications

  • Decorators rely on enclosing scopes to remember the wrapped function.
  • Linters warn when you shadow built-ins like id, list, input or sum.

Best practices

  • Keep scopes small and functions short.
  • Never name variables after built-ins.
  • Prefer returning values to rebinding outer variables.

Common mistakes

Shadowing built-ins

Avoid

sum = 0
for x in data:
sum += x
print(sum([1, 2])) # TypeError

Prefer

total = 0
for x in data:
total += x

Naming a variable after a built-in hides the built-in for the rest of the scope.

Rebinding an enclosing variable without nonlocal

Avoid

def outer():
n = 0
def inc():
n += 1

Prefer

def outer():
n = 0
def inc():
nonlocal n
n += 1

Without nonlocal, n is local to inc and read before assignment.

Important notes

  • You can list a scope's names with locals() and globals() while debugging.

Key takeaways

  • Name lookup follows Local → Enclosing → Global → Built-in.
  • nonlocal and global allow rebinding outer names.
  • if/for blocks don't create new scopes, but comprehensions do.

Try it yourself

  1. 1
    Write make_accumulator() returning a function that adds numbers to a running total using nonlocal.
  2. 2
    Predict the output of a three-level nested function that prints the same name at each level, then run it.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic