What is a Namespace in Python?
The namespace is a container with a name collection in Python. There is an associated value for each name with the object. You can organize and manage identifiers. For example, variable names, function names, and class names. You can differentiate between identifiers with the same name but defined in different contexts. Python can interpret and detect them. Python avoids naming conflicts using namespaces. Note that namespaces are created automatically by the Python interpreter. When you define a variable or function, it is added to the namespace currently in scope. The scope is the area. You can access various variables and functions within its scope.
Table of Contents
Why Do We Need Namespaces?
There are various reasons why we need namespaces in Python. These are explained below.
1. It avoids name conflicts
We use namespaces to avoid naming conflicts. You can organize identifiers into separate containers. If you do not use namespaces, then there can be value overwriting by other variables and methods unintentionally.
2. You manage Scopes of variables
We can manage the scope of various variables. Each variable has its scope. You can find an identifier’s scope in different parts of the code and how it interacts with other identifiers.
3. It avoids polluting the Global Namespace
Name conflicts can exist in code without namespaces because all identifiers will be in the global namespace. These global namespaces can cause conflicts in the code. However, you can limit the scope of identifiers by using namespaces.
4. Encapsulation and Modularity
It is easy to create program components within their namespaces. It is easy to encapsulate and modularize namespaces. It allows for separate functionality and reduces dependencies between different parts of the code.
5. Name Aliasing and Importing
You can also import a module into your script. You can access and use variables and methods of imported modules using the dot operator in your script. You can use alias names if there are conflicts in the script.
Key takeaways
- You can use namespaces to map names to objects.
- Namespaces are just like dictionaries with keys and values.
- We use namespaces to avoid naming conflicts.
- There are four types of namespaces in Python: Built-in, Global, Local, and Enclosing.
- You can use globals() and locals() functions to access the global and local namespaces, respectively.
- You can create and manage your namespaces.
Types of Namespace
There are four types of namespaces in Python.
1. Built-in Namespace
This built-in namespace contains all the built-in namespace variables and methods in Python. Python interpreters can call built-in namespaces, which are available for all modules and scripts.
For example, accessing built-in functions and objects:
print(len([1, 2, 3])) # built-in function 'len'
print(int('10')) # built-in object 'int'
Output:
The print(), len(), and int() functions are part of the built-in namespace because they are built-in functions of Python. All the built-in functions of Python are part of the built-in namespace.
2. Global Namespace
The global namespace contains all variables and functions defined at the script’s top level. Global namespaces are available for all modules and scripts.
For example,
# Global variable
global_var = 'Welcome to EDUCBA'
# Accessing global variable within a function
def func():
print(global_var)
func() # Calling the function
Output:
The global_var is defined at the top level and can be accessed anywhere in this program. It is part of the global namespace. We can access and print global_var from the function func() in the above code.
3. Local Namespace
The local namespace contains all variables and functions defined within a function. The local namespace is only available to the function that defines it.
For example, accessing local variable within a function:
def func():
local_var = 'Learn python tutorial in EDUCBA'
print(local_var)
func() # Calling the function
Output:
The func() has a local variable, local_var. It can be accessed and used only within this function. If you try to access it outside of this function, it will return a NameError.
4. Enclosing Namespace
The enclosing namespace contains all variables and functions defined in a nested function’s enclosing function. When called, a nested function creates it and continues to exist until the nested function returns. The enclosing namespace is available to the nested function that defines it.
For example,
def func():
# Outer function
def outer_func():
outer_var = 'outer'
# Inner function
def inner_func():
print(outer_var)
inner_var = 'inner'
inner_func() # Calling the inner function
# print(inner_var) # Trying to print variable defined in the inner function
outer_func() # Calling the outer function
Output:
Note:
- We have defined outer_var in the outer_func (global namespace for inner_function).
- We have defined inner_var in inner_func() (global namespace for inner_function).
If you try to access inner_var outside of inner_func(), you will get the following error:
This error occurs because the variable “inner_var” is not defined in scope.
Scope and the LEGB Rule (Local, Enclosing, Global, Built-in)
We defined a variable’s scope as where it can be accessed and used. We use Python’s LEGB (Local, Enclosing, Global, Built-in) rule.
LEGB stands for:
- Local: The local scope is the current function.
- Enclosing: The enclosing scope is the scope of the function that contains the current function.
- Global: The global scope represents the module’s scope where the current function is defined.
- Built-in: The built-in scope is the scope of the Python interpreter itself.
The note specifies the usage of the lambda expression as a function.
When you need to find a variable’s value, it searches for it first in the local scope. If you do not find it in the local scope, it searches for it in the enclosing scope, the global scope, and finally, the built-in scope.
We use LEGB rules to avoid name collisions. For example, if you have a variable named x in the global scope and x in the local scope, Python will use the local variable x when it is inside the function.
Example
For example, consider this code for how the LEGB rule works:
x = 30 # 3. Global variable for both the inner_function and outer_function
def outer_function():
x = 20 # 2. Enclosing scope variable for inner_function
# And it also a local variable of outer_function
def inner_function():
x = 10 # 1. Local variable for inner_function
print(x)
inner_function()
outer_function()
In this code, we have defined the variable x in three places: in the local scope of inner_function(), in the enclosing scope of inner_function(), and in the regional scope of outer_function(). We have defined the global scope of both the inner_function and outer_function.
Now, if you execute this code, then the output will be:
Output 1:
It prints ten because Python searches x in the local scope of this inner_function(). It found, so printed its value.
If you remove or comment out x = 10 in inner_function and execute the code, Python looks for x in the local scope of inner_function and hence does not find it. The program follows the LEGB
rule, searching the enclosing scope of the inner_function, seeing it, and printing the value of x, which is 20.
Output 2:
Practical Examples of Using Namespaces
1. Simple Examples
These are practical examples of namespaces in Python.
(a) Local Namespaces in Functions
When you define variables and functions within a function, these exist in the local namespace. You can only access it within that scope of function.
For example,
def calculate_area(length, width):
area = length * width # Local variable 'area'
return area
# Calling the function from the global scope
result = calculate_area(5, 3)
print(result)
This code defines the area as a local variable within the calculate_area() function. It does not conflict with variables of the same name from outside the function.
Output:
(b) Avoiding Conflicts with “from math import *.”
You should use “from math import *” carefully because there can be naming conflicts. So, you should import your specific functions to avoid naming conflicts.
For example,
# Potential conflict with a built-in function
from math import * # Not recommended
# Safer approach: import specific functions
from math import pi, sqrt
Now, you need not worry about names other than pi and sqrt.
2. Module Organization
You can organize your code into modules, structure it logically, and reuse it anywhere in your project code. Namespaces are defined within the module.
(a) Defining Functions and Variables in Modules
For example, consider the geometry.py module. We have defined two functions to calculate area and circumference. Whatever you define within this module will be its only namespace.
For example,
# geometry.py
PI = 3.14159 # Module-level variable
def calculate_area(length, width):
area = length * width
return area
def calculate_circumference(radius):
circumference = 2 * PI * radius
return circumference
The namespace of this module has PI, calculate_area() and calculate_circumference(). You can access these using dot notation, such as geometry.calculate_area() or geometry.PI.
(b) Importing and Using Modules
Now, you can use the above functions after importing their module into your script. You can use those namespaces after importing their modules.
For example, you can import the above geometry module into your main script code like this:
# main.py
import geometry
# Using functions from the geometry module
rectangle_area = geometry.calculate_area(5, 3)
print("Area of rectangle:", rectangle_area)
circle_circumference = geometry.calculate_circumference(3)
print("Circumference of circle:", circle_circumference)
In this code, we have imported the geometry module using the import statement, which will also import its namespace into this main code. Now, you can access and use functions and variables defined in the geometry module using dot notation.
You can execute the above code in VS Code. You need to put these scripts in the same folder, open VS Code, and then navigate to that open folder from the command prompt. Then execute using the following command:
python main.py
Output:
Hence, you can import and use variables and functions from the other module in your script.
Advanced Considerations
1. Namespaces and Classes
In Python, classes are also namespaces. When you create a class, you create a new namespace for this class’s attributes and methods. Also, each class instance has its namespace for that instance variables.
(a) Class Namespace
Consider this example,
class Car:
wheels = 4 # Class-level attribute
def __init__(self, make, model):
self.make = make # Instance variable
self.model = model # Instance variable
def drive(self):
print("Driving the", self.make, self.model)
In this code, we have defined the Car class with the wheels attribute and the __init__() and drive() methods belonging to the class namespace.
(b) Instance Namespace
my_car = Car("Toyota", "Camry")
When you create an instance (i.e., my_car) of this Car class, it will have its namespace with variables make and model. Note that each instance of the same class will have its namespace.
2. Dynamic Creation of Namespaces
In Python, you can dynamically create namespaces during runtime. It allows you to add dynamic attributes to objects, and you have the flexibility to create these namespaces based on conditions.
(a) Dynamic Creation of Attributes
For example, consider this code,
class Person:
pass
person = Person()
person.name = "Ay" # Dynamically adding 'name' attribute
person.age = 30 # Dynamically adding 'age' attribute
The Person class does not have name and age attributes in this code. So, we have added name and age attributes dynamically to the class object.
(b) Dynamic Creation of Namespaces
You can also define namespaces dynamically. For example,
namespace_dict = {'name': 'Monica', 'age': 24}
namespace = type('Namespace', (), namespace_dict)
print(namespace.name) # Accessing dynamically created namespace
print(namespace.age)
In this code, we have defined a dictionary named namespace_dict with keys and values. We then use the type() function to create a class Namespace with attributes defined in namespace_dict dynamically. Now, you can access and use these variables.
Output:
Best Practices for using namespaces and scope
- You should avoid using global variables. Use local variables whenever possible.
- You can create global variables using global keywords whenever a function needs them.
- You should use descriptive names for your variables, functions, and classes.
- You can use functions and classes to encapsulate code and avoid namespace pollution.
- You can use the nonlocal keyword to access variables in the enclosing scope of a nested function.
- You can use namespaces to create private variables.
Conclusion
Namespaces organize and manage identities such as variables, functions, and classes. This organization helps prevent naming conflicts within the given scope. There are four types of namespaces: built-in, local, enclosing, and global. We apply LEGB rules for namespaces in Python. Python initially searches for a variable in the local scope; if not found, it searches in the enclosing function, followed by the global scope. If the variable is still not found, Python searches the built-in namespaces. If the variable remains undefined in these scopes, it returns a name error. You should follow naming conventions to maintain consistency in your project code. Furthermore, Python allows for the creation of dynamic namespaces for classes.
Frequently Asked Questions (FAQs)
Q1: How does Python handle namespace conflicts when using multiple modules in a project?
Answer: You can alias them using the “as” keyword in Python. So, you can access variables and functions from different modules without conflicts.
Q2: Is it possible to have nested namespaces in Python?
Answer: Yes. In Python, nested namespaces can exist. When defined within another function, it creates a nested namespace. Nested namespaces follow the LEGB (Local, Enclosing, Global, Built-in) rule for variable resolution.
Q3: Can namespaces be deleted/ modified during runtime in Python?
Answer: Yes, namespaces can be modified during runtime in Python. You can add, remove, and change variables, functions, and classes dynamically within a namespace.
Recommended Articles
We hope that this EDUCBA information on “Namespace in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information,