Namespace
In Python, a namespace is a container that holds a collection of identifiers, such as variable and function names, and their corresponding objects. It serves as a mapping between names and objects, ensuring that each name is unique within its scope.
Namespaces help avoid naming conflicts by providing a way to organize and manage the different identifiers in a program.
Python has different namespaces, including the built-in, global, local, and non-local namespaces:
- A local namespace is created for a function when the function is called and is deleted when the function returns.
- The global namespace for a module exists for the duration of the program execution.
- The built-in namespace contains functions and types that are always available in Python, such as
len()
andstr
.
Python Namespace Example
Here’s an example to illustrate the concept of namespaces:
# Global namespace
x = "global x"
def function():
# Local namespace
x = "local x"
print(x)
function() # Output: local x
print(x) # Output: global x
In this example, the variable x
is defined in both the global and local namespaces. When you call function()
, Python looks for x
in the local namespace first and finds it. As a result, you get "local x"
. Outside the function, x
refers to "global x"
in the global namespace.
Related Resources
Tutorial
Namespaces and Scope in Python
In this tutorial, you'll learn about Python namespaces, the structures used to store and organize the symbolic names created during execution of a Python program. You'll learn when namespaces are created, how they are implemented, and how they define variable scope.
For additional information on related topics, take a look at the following resources:
- Python Scope & the LEGB Rule: Resolving Names in Your Code (Tutorial)
- What's a Python Namespace Package, and What's It For? (Tutorial)
- Variables in Python: Usage and Best Practices (Tutorial)
- Navigating Namespaces and Scope in Python (Course)
- Namespaces and Scope in Python (Quiz)
- Variables in Python (Course)
- Variables in Python: Usage and Best Practices (Quiz)