Namespaces in Python are used as an identifier in Python. Python programming is a very popular language among the developers worldwide which is due to its ease of learning and simpler syntaxes. It is important to be familiar with the naming rules in the Python programming language.Â
In this blog, we will learn more about namespaces in Python and their importance in programming. We will also learn how to assign namespace to a variable in Python language.
What Is Namespace In Python?
Namespaces in Python are used to map the keys and value pairs where the identifiers like Variable names, function names, etc are mapped to a object and connect them together. Namespaces in Python are used to collect various names and store their values in a program.Â
The use of namespaces in Python allows using the same name for different variables in different parts of the program without generating any conflict or confusion.
Types of Python Namespaces
There are three major types of Python Namespaces, let us check below.
1. Global Namespace
This namespace is for all names in the current Python module. In this namespace, any variable, function, classes are stored in the global namespace. Global namespaces in Python are built when a module is included and exist as long as the script is running.Â
x = 10Â Â
def my_function(): Â Â Â Â y = 5Â |
Here, the x variable is the global namespace and the y variable is the local namespace.Â
Read More:Â Python Full Stack Developer Roadmap For Beginners In 2025
2. Local NamespaceÂ
A local namespace exists within a function, class, or a method which stores the variable, name or entity only inside a particular function or method. Each time a function is called a new local namespace is created.Â
It exists temporarily when the function is called and is destroyed as soon as the function exists.
def my_function(a, b):
    result = a + b # ‘a’, ‘b’, and ‘result’ are in the local namespace     return result |
3. Built-In Namespace
This is the namespace that contains all built in objects, functions, and exceptions in Python. Some examples of built in namespaces in Python are print(), str, int, etc. It is created when the Python interpreter starts and lasts until the interpreter terminates.
# Using the built-in print() function
print(“Hello, World!”) # Using the built-in len() function my_list = [1, 2, 3, 4] print(len(my_list))Â |
Python Variable Scope
The concept of scope comes whenever we discuss Python namespaces. A scope is a part of a program or portion where we can access a particular variable, method, function or class directly without using any prefix.Â
Whenever a reference is made inside a function then the name inside the function is searched in the local namespace first and then the global namespace and in the last built in namespaces in Python.
# global_var is in the global namespace
global_var = 100 def outer_function():     # outer_var is in the enclosing namespace (outer function)     outer_var = 200     def inner_function():         # inner_var is in the local namespace (inner function)         inner_var = 300         # Access to all three scopes: Local, Enclosing, and Global         print(“Inner function:”)         print(“Local variable (inner_var):”, inner_var)         print(“Enclosing variable (outer_var):”, outer_var)         print(“Global variable (global_var):”, global_var)     # Print outer variable from the enclosing namespace     print(“Outer function:”)     print(“Enclosing variable (outer_var):”, outer_var)     # Call the inner function     inner_function() # Print the value of the global variable print(“Global scope:”) print(“Global variable (global_var):”, global_var) # Call the outer function to access local and enclosing scopes outer_function() |
OutputÂ
In the above example, global_var is defined at the top level of the script and can be accessed throughout the program and hence it is printed as global scope. The variable outer_var is defined inside the outer_function() and is a part of the enclosing namespace when the inner_function is called.Â
The variable inner_var is defined inside the inner_function(). This variable is a part of the local namespace specific to inner_function.Â
Lifetime of Namespaces In Python
A lifetime of a namespace in Python is defined by the scope of an object. If the scope of the object ends then the lifetime of the namespace also comes to an end.Â
- Global namespace can be accessed from anywhere in the program.
- Local namespace can only be accessed within the defined scope i,e. Function, class or methods.
x = 5
def first_func(): Â Â Â Â Â Â y = 6 Â Â Â Â Â def inner_func(): Â Â Â Â Â Â Â Â Â Â Â z = 7 |
Here, x is defined in the global namespace and y, z are defined in a local namespace.
Read More:Â How to Implement Command Line Argument using Argparse in Python?
The LEGB Rule for Searching Names In Python Namespaces
The LEGB rule for Namespaces in Python defines the order in which Python searches for a name when you use it in your program.Â
- L (Local): These names are assigned within a function or lambda expression within a limited scope.
- E(Enclosing): The names in this scope of any enclosing functions i,e. Outer function but not in the global scope.
- G(Global): These names are defined at the top level of a program or module. It can be accessed from anywhere in the program.
- B(Built-in): These namespaces are built in Python modules like print(), len(), int(), max(), and more.
When Python encounters a name it starts searching in the order where it starts from local namespace and then moving to enclosing namespace and if not found it moves to the global namespace and finally it is searched in the built in namespaces in Python.
# Global Namespace
x = 10 # This is in the global scope def outer_function():     # Enclosing Namespace     x = 20 # This ‘x’ is in the enclosing function scope     def inner_function():         # Local Namespace         x = 30 # This ‘x’ is local to the inner function         print(“Local x:”, x) # This will print the local x (from inner_function)     # This will access the enclosing function’s ‘x’     print(“Enclosing x:”, x)     # Call the inner function which uses the local ‘x’     inner_function() # Print the global ‘x’ print(“Global x:”, x) # Call the outer function outer_function() |
Output
First we print the x in the global scope and inside the outer_function(), x = 20 is defined which is used when we print the value of x within the outer_function(). The value of x = 30 when we print it inside the inner_function(). If there are no x variables in any of the above scope then Python will check it in built-in Function.
Benefits of Using Namespaces In Python Language
Let us know some of the major benefits of using namespaces in Python below.
- Namespaces ensures that variables with the same name do not get conflicted with each other especially when working on a large project.
- By using variables within the specific namespaces i,e. Local or global, Python avoids accidental overwriting or shadowing of variables.
- Namespaces in Python also improves code clarity and structure using scope.Â
- When you use namespaces in Python then it prevents you from mistakenly overwriting the wrong variable and ensuring that the correct variable values are accessed.
- With namespace functions and variables from multiple modules can be reused without worrying about the name clash.
- With namespaces in Python, it becomes easy to manage memory by limiting the lifespan of a variable to their respective namespace.Â
These benefits ensure that users can easily access and use any variable within a Python program.Â
Learn Python Programming with PW Skills
Build your knowledge of Python programming and Data structures with PW Skills self paced online program Decode DSA With Python. Get in-depth tutorials of all fundamentals and concepts in Python language. Practice real world problems, frequently asked questions, module level assignments and hands on training with industry based projects.
Master competitive programming with this course, complete all assessments and strengthen your portfolio with industry recognised certification only at pwskills.com
Namespaces In Python FAQs
Q1. What are Namespaces In Python?
Ans: Namespaces in Python are used to map the keys and value pairs where the identifiers like Variable names, function names, etc are mapped to an object and connect them together.
Q2. What are the types of Namespaces in Python?
Ans: Local, global, built-in and enclosing namespaces are four major types of namespaces in Python.
Q3. What is __init__ in Python?
Ans: The __init__ in Python is a built-in namespace which is a special method also known as a constructor. It is automatically called when a new object in the class is created.
Q4. What is called space in Python?
Ans: Space or whitespace in Python is used for spacing with an empty representation. It refers to the tabs and spaces available in the Python between any two variables or entities.