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
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
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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?
Q2:Explain the LEGB rule.
Q3:When is the global keyword required?
Q4:What causes UnboundLocalError?
Q5:What is the difference between global and nonlocal?
Q6:How are scope and lifetime different?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: