In Python, a namespace is a container that holds a set of names (identifiers) and their corresponding objects. It serves as a mapping between names and objects, allowing you to organize and manage the scope of variables, functions, classes, and other identifiers in your code. Namespaces help avoid naming conflicts and provide a way to access and reference objects in a structured manner.
There are several types of namespaces in Python:
- Local Namespace (Local Scope):
The local namespace refers to the set of names defined within a function or method. It is created when the function is called and is destroyed when the function exits.
Example:
def my_function():
local_variable = 10
print(local_variable)
my_function()
# The local_variable is part of the local namespace of my_function
2. Enclosing Namespace (Enclosing Scope):
The enclosing namespace refers to the set of names in the outer function (if any) when a function is defined inside another function (nested functions).
Example:
def outer_function():
outer_variable = 20
def inner_function():
print(outer_variable)
inner_function()
3. Global Namespace (Global Scope):
The global namespace refers to the set of names defined at the top level of a module or script. These names are accessible throughout the entire module.
Example:
global_variable = 30
def my_function():
print(global_variable)
my_function()
4. Built-in Namespace:
The built-in namespace contains the names of Python built-in functions and types. These names are always available without the need for an import statement.
Example:
print(len([1, 2, 3])) # 'len' is a built-in function
Namespaces help in organizing code, avoiding naming conflicts, and providing a clear structure for variable and function scopes. Understanding how Python namespaces work is essential for writing maintainable and readable code.