How to Use Namespaces in Python

How to Use Namespaces in Python

7 mins read607 Views Comment
Updated on Jan 12, 2023 12:09 IST

Namespace in python is a mapping from names to objects. It is a way to organize the symbols of a program by putting them in different contexts. In this article, we will learn how to use python namespace, its types.

2023_01_MicrosoftTeams-image-116-1.jpg

Namespace in python is a collection of currently defined symbolic names along with information about the object that each name references. In simple terms, Namespace is a system that has unique name for each and every object in the python.

So, without further delay let’s move to learn more about namespaces in python.

Table of Content

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
3 hours
Free
19 hours
– / –
16 weeks
Free
2 hours
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
40 hours

What is Python Namespace?

In Python, a namespace is a mapping from names to objects. It is a way to organize the symbols of a program by putting them in different contexts.

Each module in Python has its own private symbol table, which is used to store the names defined in that module. This table is called the module’s namespace. When a module is imported, all the symbols in the module’s symbol table are made available to the caller, but they are put into the module’s namespace, rather than the caller’s. This way, it is not possible for the caller to accidentally overwrite a symbol that is defined in the module.

Here’s an example of how you can use namespaces in Python:

 
# define a function in the global namespace
def func():
print("I am a function in the global namespace")
# define a variable in the global namespace
x = 10
def main():
# define a function in the local namespace
def func():
print("I am a function in the local namespace")
# define a variable in the local namespace
x = 20
# use the global function
func() # prints "I am a function in the global namespace"
# use the local variable
print(x) # prints 20
main()
Copy code

In this example, the func and x defined in the main function are said to be in the local namespace, while the func and x defined at the top level of the script are in the global namespace. When you call func() inside main, it will use the func in the local namespace, because it is defined there. However, if you try to access x inside main, it will use the x in the global namespace, because there is no x defined in the local namespace.

What is Programming What is Python
What is Data Science What is Machine Learning

Types of Namespaces in Python:

In Python, there are several types of namespaces that can be used to organize symbols:

  • Global namespace: This is the namespace that contains all the symbols that are defined at the top level of a module or script.
  • Local namespace: This is the namespace that is created whenever you define a function or method. It contains all the symbols that are defined within the function or method.
  • Module namespace: This is the namespace that contains all the symbols that are defined in a module.
  • Built-in namespace: This is a predefined namespace that contains all the built-in symbols that are available in Python, such as int, str, list, and so on.

Now, let’s look into each category in detail.

Global namespace:

In Python, the global namespace is the namespace that contains all the symbols that are defined at the top level of a module or script. These symbols can be accessed from anywhere in the module or script, and are said to be in the global namespace.

For example, consider the following script:

 
# define a function in the global namespace
def func():
print("I am a function in the global namespace")
# define a variable in the global namespace
x = 10
def main():
# access the function and variable in the global namespace
func() # prints "I am a function in the global namespace"
print(x) # prints 10
main()
Copy code

In this example, the func and x defined at the top level of the script are in the global namespace. They can be accessed from anywhere in the script, including from within the main function.

Local namespace:

In Python, a local namespace is a namespace that is created whenever you define a function or method. It contains all the symbols that are defined within the function or method and are said to be local to that function or method.

For example, consider the following script:

 
def main():
# This is an example of the local namespace
# define a function in the local namespace
def func():
print("I am a function in the local namespace")
# define a variable in the local namespace
x = 20
# use the function and variable in the local namespace
func() # prints "I am a function in the local namespace"
print(x) # prints 20
main()
Copy code

In this example, the func and x defined inside the main function are in the local namespace. They can only be accessed from within the main function, and are not visible outside of it.

Module namespace:

In Python, a module namespace is a namespace that contains all the symbols that are defined in a module. When you import a module, all the symbols in the module’s namespace are made available to the caller, but they are put into the module’s namespace, rather than the caller’s. This helps to prevent the caller from accidentally overwriting symbols that are defined in the module.

For example, consider the following module my_module.py:

 
# define a function in the module namespace
def func():
print("I am a function in the module namespace")
# define a variable in the module namespace
x = 10
Copy code

To use this module in another script, you can use the import statement:

 
import my_module
# access the function and variable in the module namespace
my_module.func() # prints "I am a function in the module namespace"
print(my_module.x) # prints 10
Copy code

In this example, the func and x defined in my_module are said to be in the module namespace. When you access them using the my_module prefix, you are accessing the symbols in the module’s namespace.

Built-in namespace:

In Python, the built-in namespace is a predefined namespace that contains all the built-in symbols that are available in Python. These symbols include functions, classes, and variables that are defined in the Python Standard Library and are always available to use in your Python programs.

Here are a few examples of symbols that are defined in the built-in namespace:

  • int: This is the class for representing integers.
  • str: This is the class for representing strings.
  • list: This is the class for representing lists.
  • print: This is a function that prints the specified objects to the standard output stream.
  • len: This is a function that returns the length of an object.

You can access these symbols simply by using their names, without having to import them from any module. For example, you can create a string by calling str(), create a list by calling list(), and print to the console by calling print().

Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications

Scope of a Variable/Object in Python:

In Python, scope refers to the visibility and accessibility of variables within a program. A variable’s scope determines where it can be used and accessed in the program.

There are two types of scope in Python:

  • Global Scope
  • Local Scope.

 A global variable is one that is defined outside of any function or class and is accessible from anywhere in the program. A local variable, on the other hand, is one that is defined within a function or class and is only accessible within that function or class.

For example, consider the following code:

 
x = 10 # global variable
def foo():
y = 5 # local variable
print(x) # prints 10
print(y) # prints 5
foo()
# generates an error because y is a local variable
# and cannot be accessed outside of the function foo
print(y)
Copy code

In this code, the global variable x is defined outside of any function and is therefore accessible from anywhere in the program. The local variable y is defined within the function foo and can only be accessed within that function. When we try to access y outside of the function, an error is generated because y is not in scope.

Access Namespaces in Python:

To access the global namespace in Python, you can simply use the name of the variable you want to access. 

For example:

 
x = 10 # global variable
def foo():
print(x) # prints 10
foo()
Copy code

To access the local namespace, you can use the built-in function locals(). This function returns a dictionary containing all of the variables in the current local namespace.

 For example:

 
def foo():
x = 10 # local variable
y = 15 # local variable
print(locals()) # prints {'x': 10, 'y': 15}
foo()
Copy code

You can also access specific variables within the local namespace by using the dictionary returned by locals(). 

For example:

 
def foo():
x = 10 # local variable
y = 15 # local variable
print(locals()['x']) # prints 10
foo()
Copy code
About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio