PythonPython Variables and Data TypesPython variables

What is variable scope in Python?

Question 40 of 88 · Updated

On this page

Variable scope is the region of a Python program in which a particular name binding is directly accessible. Scope determines which object a name refers to when Python evaluates it, and where assignments create or change bindings.

Python generally uses lexical scoping: the structure of the source code, rather than the chain of functions that happen to call one another, determines the enclosing scopes available to a function.

Understanding scope helps prevent accidental global state, unexpected name shadowing, NameError and UnboundLocalError.

1. Names, bindings, namespaces and scope#

These terms are related but describe different concepts.

TermMeaning
NameAn identifier such as score
BindingThe association of a name with an object
NamespaceA collection of name-to-object associations
ScopeThe region in which a binding is directly accessible
Object lifetimeHow long an object continues to exist

A name can refer to different objects in different scopes. Several names can also refer to the same object. Scope does not directly determine when an object must be destroyed: an object can remain reachable through another reference after a particular local scope has finished executing.

2. Local scope#

A function's parameters and ordinary assignments inside the function generally introduce local names, unless a declaration changes their binding rules.

PYTHON
score = 10 def report(): score = 20 print(score) report() print(score)

Output:

20
10

The score inside report is a local binding. The module-level score remains 10. The identical spelling does not mean both names have the same binding.

Each ordinary function invocation has its own local execution context. Local variables are useful for temporary calculations and intermediate results that should not be shared across unrelated calls.

3. The LEGB lookup rule#

For ordinary name references in functions, Python's scope resolution is commonly explained with LEGB:

  • Local (L): Names in the current function's local scope.
  • Enclosing (E): Names in lexically enclosing function scopes, from the nearest relevant scope outward.
  • Global (G): Names in the module namespace associated with the function.
  • Built-in (B): Names in the built-in namespace, such as len and print.
Loading diagram…

This simplified diagram covers ordinary function-name resolution. An unbound free variable can also raise NameError. Explicit global and nonlocal declarations affect classification, and class bodies, comprehensions, annotation scopes and dynamic execution have additional rules.

LEGB should not be understood as a universal runtime search that falls back to a global value whenever a local name has not yet been initialized. Python first determines the binding category of a name in a code block. That distinction is especially important when diagnosing UnboundLocalError.

4. Enclosing scope#

A function defined inside another function can access suitable names from the outer function's lexical scope.

PYTHON
label = 'module' def outer(): label = 'outer' def inner(): print(label) inner() outer()

Output:

outer

The inner function has no local binding of label. It resolves the name to the outer function's binding rather than the module-level value.

If multiple enclosing functions are involved, the nearest applicable lexical binding takes precedence. The important relationship is the nesting of definitions, not simply which function calls inner.

5. Global and built-in scopes#

A module-level name is often called a global variable. In Python, global normally means the namespace of a particular module, not a single universal namespace shared by every module.

A function can read a module-level name when it has no applicable local or enclosing binding that takes precedence.

Built-in names are available without importing an ordinary module binding for each name.

PYTHON
def size(items): return len(items) print(size([1, 2, 3]))

Output:

3

The parameter items is local to size. The name len is resolved through the built-in namespace in this example.

Avoid unintentionally shadowing built-ins with names such as list, dict, len or sum. For instance, assigning len = 3 in a module and then calling len([]) normally raises TypeError because the name now resolves to an integer, not the built-in function.

6. Reading versus rebinding with global#

Reading a module-level name does not generally require a global declaration. Assigning to that name inside a function, however, ordinarily makes it local to that function.

The global keyword declares that a particular name in the current code block refers to the module-level binding.

PYTHON
count = 0 def increment(): global count count += 1 increment() print(count)

Output:

1

Without the declaration, count += 1 would normally be classified as a local read and assignment, leading to UnboundLocalError because the local binding has not been initialized.

The global declaration affects a name's binding rules; it does not make an object immutable or make updates safe under concurrency. Prefer explicit function arguments and return values when they express the operation more clearly.

7. Rebinding an enclosing variable with nonlocal#

The nonlocal keyword allows a nested function to rebind an existing name in an enclosing function scope.

PYTHON
def outer(): count = 0 def increment(): nonlocal count count += 1 return count return increment counter = outer() print(counter(), counter())

Output:

1 2

The returned function retains access to its enclosing binding of count. The nonlocal declaration makes assignment update that binding rather than introducing a new local variable.

A nonlocal declaration must refer to an existing binding in an appropriate enclosing function scope. It does not target module globals. A declaration without a suitable enclosing binding is a SyntaxError.

This example introduces closure behavior only as needed to explain scope. Separate closure and function-scope lessons can explore captured bindings and late binding in more detail.

8. Python does not generally create a new scope for if and for blocks#

Ordinary if, for, while, with and try statements do not create independent lexical variable scopes merely by introducing an indented block.

PYTHON
def report(): if True: label = 'ready' for i in range(2): pass print(label, i) report()

Output:

ready 1

Both names are local to report, and their assignments have executed before the print statement.

This does not mean a name is always initialized after a conditional or loop. A branch may not execute, and a loop may have no iterations. Accessing an uninitialized local name can raise UnboundLocalError.

Some constructs have special binding or cleanup rules. In particular, the target of an except clause is cleared after that clause finishes. Do not assume that all names introduced inside control-flow statements remain bound indefinitely.

9. Comprehension scope#

Python 3 comprehensions isolate their iteration variables from the surrounding ordinary scope.

PYTHON
i = 99 values = [i * 2 for i in range(3)] print(values, i)

Output:

[0, 2, 4] 99

The comprehension's iteration variable does not overwrite the outer i. This differs from an ordinary for statement.

The leftmost iterable expression is evaluated in the enclosing scope. Assignment expressions within comprehensions have special binding rules and restrictions. Implementation optimizations, including comprehension inlining in newer CPython versions, must not be confused with a change to ordinary iteration-variable isolation.

10. Class scope is not an ordinary enclosing function scope#

A class definition executes in a namespace used to construct the class. Methods do not generally resolve unqualified names through the class namespace as though it were an enclosing function scope.

PYTHON
label = 'module' class Demo: label = 'class' def show(self): return label, self.label print(Demo().show())

Output:

('module', 'class')

The unqualified label inside show resolves to the module-level name. The expression self.label performs attribute lookup on the instance, which can find the class attribute.

Name resolution and attribute lookup are different operations. A class attribute is commonly accessed through an instance or class reference, not through an unqualified name inside an ordinary method.

Class bodies, the special __class__ closure used by certain methods and newer annotation scopes have additional behavior beyond the simple LEGB model.

11. Lexical scope versus caller context#

PYTHON
label = 'module' def read(): return label def caller(): label = 'caller' return read() print(caller())

Output:

module

The local label in caller is not an enclosing lexical binding for read. The read function was defined at module level, so its ordinary global lookup finds the module's label.

This example demonstrates why Python's ordinary function scoping is lexical rather than dynamically searching the caller's local variables.

12. Mutating an object is different from rebinding a name#

PYTHON
items = [] def add(): items.append('pen') add() print(items)

Output:

['pen']

The function reads the global binding items and invokes a method on the list. It does not assign a new object to the name items, so a global declaration is unnecessary.

However, using an assignment such as items = [] inside add would introduce a local binding unless the name were declared global. An augmented assignment such as items += ['pen'] also counts as assignment to the name even when the list operation mutates in place.

Shared mutable state can be difficult to test and reason about. The absence of a global keyword does not guarantee that a function has no side effects.

13. NameError and UnboundLocalError#

A NameError generally occurs when Python cannot resolve an evaluated name. UnboundLocalError is a subclass of NameError that occurs when a name classified as local in a function is accessed before its local binding has been established.

Consider the following deliberately failing example:

PYTHON
x = 1 def f(): print(x) x = 2 f()

Expected exception: UnboundLocalError.

The assignment to x anywhere in this function body causes x to be treated as local throughout the function, absent a declaration changing that classification. At print(x), the local name has not received a value. Python does not fall back to the global x merely because it exists.

Five independent error cases were tested:

ScenarioExpected exception
print(never_defined) in a clean namespaceNameError
Read a local before its assignmentUnboundLocalError
nonlocal missing with no enclosing bindingSyntaxError
Return a local initialized only in an untaken branchUnboundLocalError
Shadow len with an integer and then call itTypeError

Use explicit initialization, function arguments, return values or a justified scope declaration to correct the underlying binding problem.

14. Inspecting namespaces#

The built-in locals() and globals() functions can help diagnose which names are available.

PYTHON
def inspect(): local_value = 7 print('local_value' in locals(), 'local_value' in globals()) inspect()

Output:

True False

globals() returns the current module's global dictionary. locals() provides the applicable local namespace representation. Its exact behavior depends on the execution scope and Python version.

In Python 3.13, optimized scopes such as ordinary functions return fresh dictionaries of local bindings from locals(). Editing these dictionaries is not a reliable way to change actual local variables. Use ordinary assignment for predictable code rather than trying to mutate local namespaces indirectly.

15. Practical example: keep calculations local#

PYTHON
def subtotal(prices, fee): return sum(prices) + fee print(subtotal([10, 20], 5)) print(subtotal([], 0))

Output:

35
0

The function receives its dependencies as arguments rather than relying on hidden global price or fee values. Its callers can provide different inputs independently, which makes testing and reuse straightforward.

For n bounded-size numeric prices, this calculation performs O(n) arithmetic work with constant auxiliary accumulator state, excluding the input and object-specific numerical costs. Real monetary computations also require an appropriate representation and rounding policy.

16. Best practices#

  • Prefer local names for temporary results and explicit parameters for dependencies.
  • Use meaningful identifiers that do not accidentally shadow built-ins.
  • Use global and nonlocal only when intentionally changing an existing outer binding.
  • Initialize names on every control-flow path that reads them.
  • Distinguish scope from object lifetime, mutability and attribute access.
  • Avoid treating module globals as universal shared state or a concurrency guarantee.
  • Keep functions focused so their inputs, outputs and side effects remain easy to understand.

Frequently asked questions#

What is the difference between local and global scope?#

Local names belong to the current function's execution context. Global names belong to a module's namespace and can be read by functions in applicable contexts.

Do if statements introduce a new scope?#

Ordinary if statements do not introduce a separate lexical scope. However, assignments inside an unexecuted branch do not establish a runtime binding.

Does a function need global to read a global name?#

No. A declaration is needed when the function intends to bind that name globally rather than locally.

Does nonlocal work at module level?#

No. It requires an appropriate enclosing function binding and does not refer to module globals.

Is LEGB applicable to every kind of Python code?#

It is a useful model for ordinary function-name resolution. Class scopes, comprehensions, annotation scopes and dynamic execution involve additional rules.

Interview-ready answer#

Variable scope determines where a Python name binding can be accessed and how a name is resolved. In ordinary functions, the LEGB rule describes local, enclosing, global and built-in scopes. Python uses lexical scoping, so enclosing function scopes depend on where a function is defined rather than who calls it. Assignment inside a function normally creates a local binding unless global or nonlocal changes that rule. Reading an uninitialized local name raises UnboundLocalError rather than falling back to a global binding. Ordinary if and for blocks do not create separate lexical scopes. Understanding these rules helps write predictable functions and avoid unintended shared state.

Official references#

Verification note: Twelve independent runnable examples and five expected-exception tests passed locally on CPython 3.13.5. The fenced Mermaid diagram was manually reviewed for name-resolution branches and the local-binding error case. The local Mermaid package and CLI were unavailable, so parser-level validation and live rendering remain unverified. Official links are supplied under the authorized offline research exception; live documentation and Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design