In Python, a namespace is a container for mapping names to objects.
It provides a way to organize and manage variables, functions, classes, and other objects in a program.
Namespaces are created and managed by Python’s runtime system and can be nested within each other.
Here is an example to understand namespace in python.
# define a namespace called 'animals'
animals = {
'dog': 'woof',
'cat': 'meow',
'cow': 'moo',
'sheep': 'baa'
}
# print the 'dog' sound from the 'animals' namespace
print(animals['dog'])
# define another namespace called 'colors'
colors = {
'red': '#FF0000',
'green': '#00FF00',
'blue': '#0000FF'
}
# print the 'red' color from the 'colors' namespace
print(colors['red'])
Types of Namespace in Python:
There are three types of namespaces in Python:
Built-in namespace:
The built-in namespace is the default namespace in Python and contains built-in functions and modules like print(), len(), math, etc.
These can be used without any import statements in your code. If you want to know about import functions in python click here.
Global namespace:
The global namespace is the namespace of the module that is currently being executed.
It contains variables, functions, and classes that are defined in the module. These can be accessed from anywhere in the module.
Local namespace:
The local namespace is created whenever a function or method is called. It contains variables, functions, and classes that are defined within the function or method.
These can only be accessed within the function or method.
To access an object in a namespace, you can use the dot notation. For example, to access a function named my_function in the global namespace, you can write my_function().
Python provides several built-in functions for manipulating namespaces, including globals(), which returns a dictionary of the global namespace, and locals(), which returns a dictionary of the local namespace.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.