Understanding namespaces and scope is crucial for managing variables effectively in Python. This tutorial will delve into the different types of scopes—local, enclosing, global, and built-in—and explain how to use the global and nonlocal keywords.
Namespaces are a fundamental concept in programming that help organize and manage variable names. In Python, each scope has its own namespace, which is essentially a dictionary mapping names (variable names) to objects (values). The scope determines where these variables can be accessed. Understanding the LEGB rule (Local, Enclosing, Global, Built-in) will help you navigate how Python resolves variable names.
The local scope refers to the namespace of a function or method. Variables defined within a function are only accessible within that function and cannot be accessed from outside it.
1def my_function():2local_var = 103print(local_var)45my_function()6print(local_var) # This will raise an error
10 Traceback (most recent call last): File "local_scope.py", line 7, in <module> print(local_var) NameError: name 'local_var' is not defined
The enclosing scope refers to the namespace of any and all enclosing functions. If a variable is not found in the local scope, Python will look for it in the nearest enclosing scope.
1def outer_function():2enclosing_var = 2034def inner_function():5print(enclosing_var)67inner_function()89outer_function()
20
The global scope is the namespace of the current module. Variables defined at the top level of a script are in the global scope and can be accessed from any function within that module.
1global_var = 3023def my_function():4print(global_var)56my_function()
30
The built-in scope contains the names of all built-in functions and exceptions. These are always available, but they can be shadowed by variables in other scopes.
1print = 40 # Shadowing the built-in print function23def my_function():4print("Hello") # This will raise an error56my_function()
Traceback (most recent call last):
File "builtin_scope.py", line 6, in <module>
my_function()
File "builtin_scope.py", line 4, in my_function
print("Hello")
TypeError: 'int' object is not callableThe LEGB rule summarizes the order in which Python searches for a variable:
global KeywordThe global keyword allows you to modify a variable in the global scope from within a function.
1global_var = 5023def my_function():4global global_var5global_var = 6067my_function()8print(global_var)
60
nonlocal KeywordThe nonlocal keyword allows you to modify a variable in the nearest enclosing scope from within a nested function.
1def outer_function():2enclosing_var = 7034def inner_function():5nonlocal enclosing_var6enclosing_var = 8078inner_function()9print(enclosing_var)1011outer_function()
80
Let's create a practical example that demonstrates the use of local, global, and nonlocal scopes.
1global_counter = 023def increment_global():4global global_counter5global_counter += 16print(f"Global counter: {global_counter}")78def outer_function():9enclosing_counter = 901011def inner_function():12nonlocal enclosing_counter13enclosing_counter += 1014print(f"Enclosing counter: {enclosing_counter}")1516inner_function()17increment_global()1819outer_function()
Enclosing counter: 100 Global counter: 1
global Keyword: Modify global variables within a function.nonlocal Keyword: Modify enclosing variables within a nested function.In the next tutorial, we will explore Python closures. Closures are functions that remember values in enclosing scopes even if they are not present in memory. Understanding closures will help you write more efficient and reusable code. Stay tuned!