How to Use Namespaces in Python
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.
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
Best-suited Python courses for you
Learn Python with these high-rated online courses
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 namespacedef func(): print("I am a function in the global namespace")
# define a variable in the global namespacex = 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()
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.
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 namespacedef func(): print("I am a function in the global namespace")
# define a variable in the global namespacex = 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()
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()
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 namespacedef func(): print("I am a function in the module namespace")
# define a variable in the module namespacex = 10
To use this module in another script, you can use the import statement:
import my_module
# access the function and variable in the module namespacemy_module.func() # prints "I am a function in the module namespace"print(my_module.x) # prints 10
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 fooprint(y)
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()
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()
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()
Conclusion:
In this article, we have covered the concept of namespaces in python in detail. We also looked into the concept of scoping for variables in python. It also provides you with information about various categories of python namespaces and their uses.
Hope you will like the article.
Top Trending Article
Top Online Python Compiler | How to Check if a Python String is Palindrome | Feature Selection Technique | Conditional Statement in Python | How to Find Armstrong Number in Python | Data Types in Python | How to Find Second Occurrence of Sub-String in Python String | For Loop in Python |Prime Number | Inheritance in Python | Validating Password using Python Regex | Python List |Market Basket Analysis in Python | Python Dictionary | Python While Loop | Python Split Function | Rock Paper Scissor Game in Python | Python String | How to Generate Random Number in Python | Python Program to Check Leap Year | Slicing in Python
Interview Questions
Data Science Interview Questions | Machine Learning Interview Questions | Statistics Interview Question | Coding Interview Questions | SQL Interview Questions | SQL Query Interview Questions | Data Engineering Interview Questions | Data Structure Interview Questions | Database Interview Questions | Data Modeling Interview Questions | Deep Learning Interview Questions |
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