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.
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
- 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
inner sees: enclosing module sees: global built-in len: 3
Loops don't create scopes
5 comprehension variable i did not leak
More examples
nonlocal and shadowed built-ins
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:
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
Prefer
Naming a variable after a built-in hides the built-in for the rest of the scope.
Rebinding an enclosing variable without nonlocal
Avoid
Prefer
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
- 1Write make_accumulator() returning a function that adds numbers to a running total using nonlocal.
- 2Predict 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?