- Courses
- 💻Programming Languages
- 🐍Python
- Functions and Modular Programming
- Scope & Lifetime
On this page
Scope & Lifetime
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Understanding Scope in Python
Scope defines where a name (variable, function, or reference) is visible and accessible in a program. Python uses a well‑defined set of rules to determine how names are resolved. Understanding these rules is essential for writing predictable, maintainable functions.
Python follows the LEGB rule, which stands for:
- Local — names defined inside the current function
- Enclosing — names in any outer function (for nested functions)
- Global — names defined at the top level of a module
- Built‑in — names provided by Python itself
When Python encounters a name, it searches these scopes in order.
Local Scope
A local scope is created whenever a function is called. Variables assigned inside a function belong to this scope.
def compute():
x = 10 # local variable
return x * 2
Key characteristics:
- Local variables exist only while the function is running.
- They cannot be accessed outside the function.
- Each function call creates a new, independent local scope.
Local scope prevents different parts of a program from interfering with each other.
Global Scope
Names defined at the top level of a file belong to the global scope.
x = 5 # global variable
def show():
print(x)
Functions can read global variables, but they cannot assign to them unless explicitly declared using global.
count = 0
def increment():
global count
count += 1
Using global is generally discouraged in modular programming because it makes code harder to reason about.
Enclosing Scope (for Nested Functions)
When a function is defined inside another function, the inner function can access names from the enclosing scope.
def outer():
message = "hello"
def inner():
print(message) # from enclosing scope
inner()
This enables patterns such as closures, where an inner function retains access to variables from its enclosing function even after the outer function has finished executing.
Built‑in Scope
Python provides a set of built‑in names such as len, range, and print. These are always available unless shadowed by a local or global name.
len([1, 2, 3]) # built‑in function
Shadowing built‑ins is a common beginner mistake:
len = 10 # shadows built‑in len()
Avoid reusing built‑in names for variables.
Variable Lifetime
Scope determines where a variable is visible; lifetime determines how long it exists.
Local Variable Lifetime
A local variable exists only during the execution of its function.
def example():
x = 10
return x
After the function returns, x is destroyed.
Global Variable Lifetime
A global variable exists for as long as the program is running.
counter = 0 # created when the module loads
Global variables persist until the program ends or the module is unloaded.
Enclosing Variable Lifetime
Variables in enclosing scopes live as long as the outer function’s frame exists. If an inner function forms a closure, those variables may persist longer.
def outer():
value = 42
def inner():
return value
return inner
Here, value remains alive because inner retains a reference to it.
Name Resolution and the LEGB Rule in Practice
Python resolves names by searching scopes in the following order:
- Local
- Enclosing
- Global
- Built‑in
Example:
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
outer()
Output:
local
Python stops searching as soon as it finds a matching name.
Why Scope and Lifetime Matter
Understanding scope and lifetime helps you:
- Avoid unintended variable shadowing
- Write predictable, modular functions
- Prevent bugs caused by accidental name reuse
- Design clean interfaces between functions
- Use closures and nested functions effectively
Scope is one of the core concepts that separates beginner code from professional‑quality code.
Summary
In this lesson, you learned how Python determines where names are visible and how long variables live. You now understand local, global, enclosing, and built‑in scopes, the LEGB resolution order, and how variable lifetime interacts with function execution. These concepts are essential for writing reliable, modular Python programs and for understanding more advanced function behavior in later lessons.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Arguments & Return Values
Next
Lambda Functions
-
Understanding Scope in Python
-
Local Scope
-
Global Scope
-
Enclosing Scope (for Nested Functions)
-
Built‑in Scope
-
Variable Lifetime
- Local Variable Lifetime
- Global Variable Lifetime
- Enclosing Variable Lifetime
-
Name Resolution and the LEGB Rule in Practice
-
Why Scope and Lifetime Matter
-
Summary
