Skip to content
PythonFunctionsbeginner18 min read

Scope and Lifetime

Understand local, enclosing, global, and built-in names, and learn how variable lifetime differs from scope.

In this lesson, you will learn

  • ✓Define scope and lifetime and explain how they differ.
  • ✓Distinguish local variables from global variables.
  • ✓Explain Python's LEGB name-resolution order.
  • ✓Read a global variable inside a function and modify it using the global keyword.
  • ✓Recognize when Python raises UnboundLocalError because a local variable is read before assignment.
  • ✓Trace nested functions and explain how enclosing-scope names are resolved.
  • ✓Write and test functions that use names within the appropriate scope.

1. What are scope and lifetime?

Scope describes the region of a program in which a name can be accessed through normal name lookup. For example, a variable assigned inside a function is normally a local name within that function.

Lifetime describes how long an object exists during program execution. Scope and lifetime are related but are not the same thing: a name may stop being accessible after a function call, while an object created during that call can remain alive if another reference still points to it.

A global variable is a name bound at the module level. A local variable is a name bound in a function's local scope. If a local name and a global name have the same spelling, the local name takes precedence when that function looks up the name.

Python determines local names in a function by examining assignments and other binding operations in the function's code, unless a name is declared global or nonlocal. This matters because a name can be treated as local even when a global name with the same spelling already exists.

A local name does not replace a global name

A local name does not replace a global name
python
message = 'outside'
 
def show():
message = 'inside'
print(message)
 
show()
print(message)
Output
inside outside

The assignment message = 'outside' creates a name in the module's global scope. Inside show(), the assignment message = 'inside' creates a local name belonging to that function call. The first print finds the local message and displays inside. The function's local assignment does not change the global message. After the function call, the final print reads the global message and displays outside.

Note

The same spelling can refer to different bindings in different scopes. To understand a program, identify which binding each use of a name refers to.

2. How Python finds a name: LEGB

Python commonly resolves an unqualified name by following the LEGB rule: Local, Enclosing, Global, Built-in. Python checks the relevant scopes in that order when looking up a name.

Local means the current function's local scope. Enclosing means the scope of an enclosing function, such as an outer function surrounding a nested function. Global means the current module's namespace. Built-in means names provided by Python's builtins, such as print() and len().

Python uses the first matching binding it finds. A local name can therefore hide a global name with the same spelling. Similarly, a name in an enclosing function can be found by a nested function when there is no matching local name.

The LEGB rule describes name lookup. It does not mean every assignment changes the first matching name. Assignment inside a function normally binds a local name unless the code declares that name global or nonlocal.

Reading a global name

Reading a global name
python
label = 'outer'
 
def show():
print(label)
 
show()
Output
outer

The function does not assign to label, so label is not made local by an assignment in show(). When print(label) runs, Python looks for label in the local scope first. No local label exists, so Python continues to the global scope and finds the value 'outer'. The function prints outer.

Note

LEGB is a useful model for ordinary function name lookup. Python's full name-resolution rules contain additional details, but these four levels explain the behavior taught in this lesson.

3. Reading and modifying global variables

A function can read a global variable without a global declaration, as long as the function does not bind that name locally. Reading and assigning are different operations.

If you assign to a name inside a function, Python normally treats that name as local throughout the function unless it has been declared global or nonlocal. If you need to rebind a module-level name, declare it with global before using that name in the function.

The global keyword tells Python that assignments to the declared name refer to the binding in the module's global namespace. It does not create a new global value by itself, and it is not needed merely to read a global name.

Although global can be useful for explaining scope, passing values as function arguments and returning updated values is often easier to test and maintain than changing global state.

Updating a global variable

Updating a global variable
python
count = 0
 
def increment():
global count
count += 1
 
increment()
increment()
print(count)
Output
2

The assignment count = 0 creates the module-level name count. The declaration global count tells Python that count += 1 refers to the global binding rather than a local name. The first call changes count from 0 to 1. The second call changes count from 1 to 2. The final print displays 2.

Caution

Do not assume Python will fall back to a global variable when a function-local name has been determined but has not yet received a value. In that situation, reading the local name can raise UnboundLocalError.

4. Enclosing scopes and nonlocal

A nested function can read a name from an enclosing function. If the nested function assigns to that name, Python normally treats the name as local to the nested function instead.

The nonlocal keyword allows a nested function to rebind a name from an enclosing function scope. The name must already exist in an enclosing function scope; nonlocal does not declare a module-level global name.

Use nonlocal when a nested function intentionally needs to update a value owned by its enclosing function. This is different from global, which refers to the module's global namespace.

Updating an enclosing variable with nonlocal

Updating an enclosing variable with nonlocal
python
def make_counter():
count = 0
 
def increment():
nonlocal count
count += 1
return count
 
return increment
 
counter = make_counter()
print(counter())
print(counter())
Output
1 2

Calling make_counter() creates a local count initialized to 0. The function returns increment, which retains access to the enclosing scope containing count. The declaration nonlocal count lets increment() update that enclosing binding. The first call changes count to 1 and returns 1. The second call changes the same enclosing count to 2 and returns 2. The returned function keeps the enclosing binding available for later calls. This illustrates why an object's lifetime is not always limited to the execution of the function that created it.

Note

Use global for a module-level name and nonlocal for a name in an enclosing function scope. Neither keyword is needed just to read an outer name.

5. Scope versus lifetime in practice

When a function call finishes, its local names are no longer available through that function's active local scope. However, an object created during the call can remain alive if a reference to it is retained elsewhere, such as in a returned value or a closure.

Do not assume that a variable name and the object it refers to have identical lifetimes. Names are bindings; objects are values that can be referenced by one or more names.

For most beginner programs, the practical rule is to keep temporary calculation variables local, use parameters to supply input, and return results instead of relying on mutable global state. This makes functions easier to reuse and test.

Returning a value from a function

Returning a value from a function
python
def make_message(name):
message = f'Hello, {name}!'
return message
 
result = make_message('Ari')
print(result)
Output
Hello, Ari!

The name parameter and the local name message are used inside make_message(). The return statement sends the string value back to the caller. The assignment result = make_message('Ari') binds the returned string to result in the module's global scope. The caller can print result even though message was local to the function.

Caution

Scope is about name accessibility; lifetime is about how long an object remains alive. Python manages object memory automatically, so avoid describing every local object as being destroyed immediately when a function returns.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Assuming a local assignment changes a global variable with the same name.

Why it happens: An assignment inside a function creates or rebinds a local name by default; it does not update a global name with the same spelling.

Incorrect Approach
script.py
python
Assuming a local assignment changes a global variable with the same name.
Correct Solution
script.py
python
An assignment inside a function normally creates or updates a local binding. Use global only when the function must rebind a module-level name.

Key takeaway: An assignment inside a function normally creates or updates a local binding. Use global only when the function must rebind a module-level name.

#2 Thinking a function needs global just to read a global variable.

Why it happens: A function can read a global name without declaring global; global is needed when rebinding that global name.

Incorrect Approach
script.py
python
Thinking a function needs global just to read a global variable.
Correct Solution
script.py
python
A function can read a global name through normal name lookup when no local binding takes precedence.

Key takeaway: A function can read a global name through normal name lookup when no local binding takes precedence.

#3 Expecting Python to use a global value when a local name is assigned later in the function.

Why it happens: Python determines a name's local status from assignments in the function body, so reading it before the local assignment can raise UnboundLocalError.

Incorrect Approach
script.py
python
Expecting Python to use a global value when a local name is assigned later in the function.
Correct Solution
script.py
python
Python determines local names from the function's code. Reading that local name before it has a value can raise UnboundLocalError.

Key takeaway: Python determines local names from the function's code. Reading that local name before it has a value can raise UnboundLocalError.

#4 Confusing global and nonlocal.

Why it happens: global refers to a module-level name, while nonlocal refers to a binding in an enclosing function scope.

Incorrect Approach
script.py
python
Confusing global and nonlocal.
Correct Solution
script.py
python
global refers to the module-level binding. nonlocal refers to an existing binding in an enclosing function scope.

Key takeaway: global refers to the module-level binding. nonlocal refers to an existing binding in an enclosing function scope.

#5 Treating scope and lifetime as the same concept.

Why it happens: Scope describes where a name can be resolved; lifetime describes how long the referenced object continues to exist.

Incorrect Approach
script.py
python
Treating scope and lifetime as the same concept.
Correct Solution
script.py
python
Scope concerns where a name can be accessed. Lifetime concerns how long an object remains alive.

Key takeaway: Scope concerns where a name can be accessed. Lifetime concerns how long an object remains alive.

#6 Using global variables for every value that functions need to share.

Why it happens: Global state couples functions and makes behavior harder to test; pass values as arguments and return results when practical.

Incorrect Approach
script.py
python
Using global variables for every value that functions need to share.
Correct Solution
script.py
python
Prefer function parameters and return values when they express the relationship clearly. This reduces hidden dependencies and makes testing easier.

Key takeaway: Prefer function parameters and return values when they express the relationship clearly. This reduces hidden dependencies and makes testing easier.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is the difference between local and global variables in Python?
Answer:
A local variable is bound in a function's local scope, while a global variable is bound in the module's global namespace. If both have the same name, the local binding takes precedence inside the function. A local assignment does not automatically change the global binding.
Q2:Explain the LEGB rule.
Answer:
LEGB stands for Local, Enclosing, Global, and Built-in. During ordinary name lookup, Python checks the relevant local scope, enclosing function scopes, the module's global namespace, and then built-ins. The first matching binding is used.
Q3:When is the global keyword required?
Answer:
It is required when a function needs to bind or rebind a module-level name using assignment. It is not required merely to read a global variable. Without a global declaration, an assignment inside a function normally makes the name local.
Q4:What causes UnboundLocalError?
Answer:
A common cause is reading a name before assigning to it inside a function. Because the function contains an assignment to that name, Python treats it as local throughout the function unless declared global or nonlocal. Reading the uninitialized local binding raises UnboundLocalError.
Q5:What is the difference between global and nonlocal?
Answer:
global refers to a binding in the module's global namespace. nonlocal refers to an existing binding in an enclosing function scope. A nested function can use nonlocal to update a variable belonging to its enclosing function.
Q6:How are scope and lifetime different?
Answer:
Scope concerns where a name can be accessed. Lifetime concerns how long an object remains alive. A local name may no longer be accessible after a function returns, while an object created during the call can remain alive if a reference to it is retained elsewhere.

Key takeaways

  • Scope describes where a name can be accessed; lifetime describes how long an object remains alive.
  • A local assignment normally creates or updates a function-local binding rather than changing a global variable.
  • Python's LEGB rule stands for Local, Enclosing, Global, and Built-in.
  • A function can read a global variable without declaring it global.
  • Use global when a function must rebind a module-level name.
  • A local name read before it has been assigned can raise UnboundLocalError.
  • Use nonlocal when a nested function must rebind an existing name in an enclosing function scope.
  • Prefer parameters and return values over unnecessary global state when designing reusable functions.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: