In Python, a namespace is a system that organizes and identifies the names of objects such as variables, functions, classes, and modules in a program. Namespaces ensure that names are unique and can be easily located and accessed in a program.
Python has four main types of namespaces:
- Built-in namespace: This namespace contains the names of built-in functions, such as
print()
andlen()
, and built-in types, such asstr
andlist
. - Global namespace: This namespace contains the names defined at the module level. These names can be accessed from anywhere within the module.
- Local namespace: This namespace contains the names defined inside a function or a block. These names can only be accessed within that function or block.
- Enclosed namespace: This namespace contains the names defined in the enclosing function of a nested function. These names can be accessed by the nested function.
Here is an example that demonstrates the use of namespaces:
# Define a variable in the global namespace
x = 10
def my_function():
# Define a variable in the local namespace
y = 20
def nested_function():
# Define a variable in the enclosed namespace
z = 30
# Access variables from all namespaces
print(x) # Access global variable x
print(y) # Access local variable y
print(z) # Access enclosed variable z
nested_function()
my_function()
In the above example, x
is defined in the global namespace, y
is defined in the local namespace of my_function()
, and z
is defined in the enclosed namespace of nested_function()
. The print()
statements inside nested_function()
demonstrate how variables can be accessed from all namespaces.