Python scope and namespaces explain where names are defined, where they can be accessed, and how Python finds the value associated with a variable or function name. Understanding scope becomes especially important when working with functions, nested functions, modules, classes, imports, and larger applications.
A namespace is a mapping between names and the objects those names refer to. A scope defines the region of a program where a particular name can be accessed directly. Python uses a well-defined lookup process called the LEGB rule to determine where it should look for a name.
Scope is not just a theoretical concept. Many common Python errors, including NameError and unexpected variable behavior inside nested functions, are caused by misunderstanding where names are created and how Python resolves them.
What Is a Namespace?
A namespace is a collection of names mapped to objects. Python uses different namespaces for different parts of a program so that names can be organized and isolated from one another.
For example, when you create a variable, the variable name becomes associated with an object in a namespace:
name = "Abhinash"
age = 30
print(name)
print(age)
The names name and age are entries in a namespace, and those entries refer to their corresponding objects.
Python's LEGB Rule
Python resolves a name using the LEGB lookup order:
L — Local
The current function or local scope where the name is being evaluated.
E — Enclosing
An enclosing function scope when nested functions are involved.
G — Global
The module-level namespace containing names defined at the top level of a module.
B — Built-in
Python's built-in namespace containing names such as len, print, and sum.
Python generally checks these scopes from the nearest applicable scope outward. Understanding this order is one of the most important steps toward understanding Python variable resolution.
Local Scope
A variable created inside a function is normally local to that function. It can be accessed from within that function, but not directly from outside it.
def calculate_total():
price = 100
quantity = 3
return price * quantity
print(calculate_total())
# print(price)
# NameError
The variables price and quantity belong to the function's local scope. Once the function finishes, those local names are no longer directly accessible from the surrounding module scope.
Global Scope
A variable defined at the top level of a module belongs to the module's global namespace. Functions can read global names when a local or enclosing name with the same identifier does not exist.
TAX_RATE = 0.18
def calculate_tax(amount):
return amount * TAX_RATE
print(calculate_tax(100))
The function can read TAX_RATE because Python does not find a local variable with that name and continues searching in the enclosing and global scopes.
The Built-in Scope
Python provides a built-in namespace containing commonly available names such as print(), len(), sum(), type(), and Exception.
numbers = [10, 20, 30]
print(len(numbers))
print(sum(numbers))
print(type(numbers))
These names are available because Python can ultimately find them in the built-in namespace when they are not shadowed by a closer name.
Enclosing Scope
Enclosing scope appears when one function is defined inside another function. The inner function can usually access names created by the outer function.
def outer():
message = "Hello from outer"
def inner():
print(message)
inner()
outer()
The inner function does not have a local variable named message, so Python continues searching and finds the variable in the enclosing outer() function.
How LEGB Works in Practice
Consider the following example where the same name exists at multiple levels:
value = "global"
def outer():
value = "enclosing"
def inner():
value = "local"
print(value)
inner()
outer()
The inner function prints "local" because Python finds the local variable first. If that local variable were removed, the enclosing variable would be found next. If there were no enclosing variable, Python would continue to the global namespace.
Reading a Global Variable
A function can normally read a global variable without using any special keyword.
application_name = "IgKnight"
def show_application():
print(application_name)
show_application()
This works because the function searches its local scope first, then continues outward until it finds the global name.
Changing a Global Variable with global
Assigning to a name inside a function normally makes that name local to the function. The global keyword tells Python that assignments to that name should target the module-level global variable.
counter = 0
def increment():
global counter
counter += 1
increment()
increment()
print(counter)
The global keyword should be used carefully. Excessive reliance on mutable global state can make programs harder to reason about and test because many different parts of the application may change the same value.
Why Assignment Can Cause UnboundLocalError
One of the most common scope errors occurs when a function both reads and assigns to a name that Python therefore treats as local.
count = 10
def show_count():
print(count)
count = 20
# show_count()
Because the function contains an assignment to count, Python treats count as a local variable within that function. The earlier print() therefore attempts to read the local name before it has a value, resulting in an UnboundLocalError.
When the intention really is to modify the module-level variable, global can make that intent explicit. In many application designs, however, passing the value into a function and returning the updated result is cleaner.
The nonlocal Keyword
The nonlocal keyword is used inside a nested function when you need to modify a variable belonging to an enclosing function rather than a global variable.
def create_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = create_counter()
print(counter())
print(counter())
print(counter())
The inner increment() function modifies the count variable belonging to create_counter(). This is a common closure pattern.
global vs nonlocal
| Keyword | Targets | Typical Use |
|---|---|---|
global |
Module-level global name | Modify a global variable from inside a function |
nonlocal |
Name in an enclosing function scope | Modify an outer function's variable from a nested function |
Nested Functions and Closures
A nested function can retain access to variables from its enclosing function even after the outer function has returned. This behavior forms the basis of closures.
def create_multiplier(factor):
def multiply(value):
return value * factor
return multiply
double = create_multiplier(2)
triple = create_multiplier(3)
print(double(10))
print(triple(10))
The returned function remembers the value of factor from its enclosing scope. Closures are useful in callbacks, factories, decorators, and configurable function behavior.
Shadowing Names
Name shadowing happens when a closer scope defines a name that already exists in an outer scope. The inner name hides the outer name for code that resolves the name from that scope.
name = "Global"
def show_name():
name = "Local"
print(name)
show_name()
print(name)
The two variables can exist independently because they belong to different namespaces. Although this is valid Python, excessive shadowing can make code harder to read.
Avoid Shadowing Built-in Names
A particularly important form of shadowing involves Python's built-in names. Creating a variable named list, str, sum, or id can hide the corresponding built-in inside that scope.
list = [1, 2, 3]
# This will fail because list now refers
# to the variable above rather than the built-in type.
# values = list((4, 5))
Use descriptive names that do not unnecessarily replace commonly used built-ins. This simple practice prevents confusing errors later.
Comprehension Scope
Comprehensions have their own iteration-variable scope in modern Python. The loop variable used inside a list, set, or dictionary comprehension does not normally leak into the surrounding scope.
numbers = [1, 2, 3]
squares = [
number * number
for number in numbers
]
print(squares)
# The comprehension variable is not
# available here as a result of the comprehension.
# print(number)
This behavior helps prevent accidental overwriting of variables outside the comprehension and is one reason comprehensions can safely use short loop-variable names within their local expression.
Class Scope and Method Lookup
Classes introduce another namespace containing class attributes and methods. However, method name resolution has some important differences from ordinary nested function scopes. A method does not automatically treat the class namespace as an enclosing function scope.
class Developer:
role = "Software Engineer"
def show_role(self):
print(Developer.role)
developer = Developer()
developer.show_role()
Inside the method, explicitly referring to Developer.role accesses the class attribute. Instance-specific data is normally accessed through self.
Module Namespaces
Every Python module has its own namespace. Variables, functions, classes, and imported names defined at the module level belong to that namespace. This is one reason modules are useful for organizing application code and avoiding unnecessary name conflicts.
# payments.py
DEFAULT_CURRENCY = "USD"
def calculate_total(amount):
return amount
Code in another module can access exported names using the module reference:
import payments
print(payments.DEFAULT_CURRENCY)
print(payments.calculate_total(100))
Using module-qualified names can make the source of a value clear and reduce accidental naming conflicts in larger applications.
Inspecting Namespaces with globals() and locals()
Python provides globals() and locals() for inspecting namespaces. They can be useful for debugging and advanced metaprogramming, but they are usually not needed in ordinary application code.
application_name = "IgKnight"
def inspect_scope():
local_value = 42
print("local_value" in locals())
print("application_name" in globals())
inspect_scope()
These functions expose namespace information, but relying on them heavily for normal application logic can make code harder to understand. Prefer explicit variables, parameters, and return values for ordinary program design.
Practical Example: Avoiding Global State
Instead of modifying a global counter, a function can receive the current value and return the updated value. This creates a clearer data flow and makes the function easier to test.
def increment(counter):
return counter + 1
count = 0
count = increment(count)
count = increment(count)
count = increment(count)
print(count)
The function does not need to know where the counter came from or where the result will be stored. The caller controls the state explicitly through arguments and return values.
Common Scope Errors
NameError
Python raises NameError when a name cannot be found in the relevant namespaces.
UnboundLocalError
This commonly occurs when Python treats a name as local because of an assignment but the function tries to read that local name before it has been assigned.
Unexpected shadowing
A local variable can hide an outer variable with the same name, leading to behavior that is valid but difficult to understand.
Incorrect global modification
Assigning to a global name inside a function without declaring it with global creates a local binding instead.
Common Mistakes with Python Scope
Using too many global variables
Excessive global mutable state creates hidden dependencies. Prefer function parameters, return values, and well-defined objects where possible.
Assuming assignment always changes an outer variable
An assignment inside a function normally creates a local binding. Use global or nonlocal only when the design specifically requires modifying an outer binding.
Shadowing built-ins
Names such as list, str, and sum should not normally be reused for unrelated variables.
Confusing class scope with enclosing function scope
A method does not automatically resolve a bare name through its class namespace the same way a nested function resolves an enclosing function variable.
LEGB Lookup Summary
| Scope | Where It Exists | Example |
|---|---|---|
| Local | Inside current function | total = 100 |
| Enclosing | Outer function containing nested function | factor = 2 |
| Global | Module level | APP_NAME = "IgKnight" |
| Built-in | Python built-ins | len, print, sum |
Best Practices for Python Scope
- Prefer local variables and explicit function parameters over unnecessary global mutable state.
- Use descriptive names and avoid shadowing important built-in names.
- Use
globalonly when modifying module-level state is genuinely required. - Use
nonlocalwhen a nested function intentionally needs to modify an enclosing function variable. - Prefer passing values into functions and returning results when that makes data flow clearer.
- Keep nested functions and closures focused on a clear purpose.
- Understand that assignment inside a function can create a local binding even when an outer variable has the same name.
- Use module namespaces to keep larger applications organized and reduce naming conflicts.
- Use
globals()andlocals()mainly for inspection or advanced use cases rather than ordinary application logic.
Why Python Scope and Namespaces Matter
Scope and namespaces determine how Python connects names to objects throughout a program. Once you understand local, enclosing, global, and built-in scopes, many confusing variable behaviors become predictable.
The most important concept to remember is the LEGB rule: Python first looks in the local scope, then enclosing scopes, then the global namespace, and finally the built-in namespace. The global and nonlocal keywords allow specific assignments to target outer scopes when that behavior is intentional.
Good scope design keeps data flow explicit. Small functions, meaningful parameters, controlled state, and limited global mutation make Python programs easier to read, test, and maintain. When scope is used deliberately, you can build larger applications without variables unexpectedly interfering with one another.