What is scope?
Scope is the region of code where a variable is accessible. Python has different scopes: local (inside a function), enclosing (outer function), global (module level), and built-in.
Local scope
Variables defined inside a function are local to that function:
def my_function():
x = 10 # Local variable
print(x)
my_function()
# print(x) # NameError: x doesn't exist outside function
Global scope
Variables defined at module level are global:
x = 10 # Global variable
def my_function():
print(x) # OK: can read global
my_function() # Prints 10
Modifying global variables
Use global keyword to modify globals:
x = 10
def modify():
global x
x = 20 # Modifies global x
modify()
print(x) # 20
LEGB rule
Python searches for variables in this order:
- Local — inside current function
- Enclosing — outer functions (for nested functions)
- Global — module level
- Built-in — Python's built-in names
Namespace
A namespace is a mapping from names to objects. Each scope has its own namespace:
# Global namespace:
x = 10
def func():
# Local namespace:
y = 20
print(x, y) # Accesses both namespaces
func()