What Are Namespaces in Python? Namespace vs Scope (Meaning, Examples)
Table of Contents
- What Is Namespace in Python?
- Example of Python Namespace
- Types of Namespaces in Python
- How to Use Namespaces in Python Programming?
- The Lifetime of a Python Namespace
- What is Scope in Python?
- Scope of Objects in Python
- Python Namespace Dictionaries
- Python Namespace vs Scope (Difference)
Namespaces and Scope are two concepts in Python used to identify variable hierarchy, which helps us understand variable behaviour. Without these two concepts, unwanted variables can get altered during execution, creating issues during programming. Also, we may have to access variables outside their scope.
Namespaces in Python help us prioritise variables with the same name, whereas Scope helps us determine the effective lifespan of a variable. These two concepts allow us to write lucid Python Programs.
This blog will explain Python namespace and scope in detail, along with types of namespace and examples for each.
What Is Namespace in Python?
In Python, there are libraries, variables, functions, and modules. So, there are high chances that the name of a variable you choose already exists as the name of another variable, function, or method. So, in such circumstances, we need to know how Python manages these names. This concept is referred to as Namespace.
So, a namespace in Python is a system where each object, be it a variable or method, has a unique name.
Python has its own way of managing and maintaining all these names and the concept of namespace in the form of a Python dictionary.
Example of Python Namespace
One example of namespace in Python is a directory-file system in computers. There can be multiple directories with a file of the same name within every directory. However, it can be possible to get directed to the required file by specifying the absolute path of that file.
Namespace works similarly to a surname in the real world. You might find multiple people with the same name in a class, say Ryan. However, when you say Ryan Thomas or Ryan Lee (adding a surname), there will be just one person with that name.
Python Compiler knows what variable or method the user is pointing to in the code based on the namespace. The division of the word provides a bit more information.
Name- a unique identifier
Space- points to something related to the scope
Here, the name can be a Python variable or method, and space is based on the location from where you are accessing an object.
Types of Namespaces in Python
The following Venn diagram shows various types of namespace in Python.
1. The Built-in Namespace
This is the highest-level namespace in Python available as default names as part of the Python interpreter loaded as the programming environment.
As the name suggests, the built-in namespace contains pre-defined names of Python’s objects, such as variables and functions. It is created at the beginning of the Python interpreter and exists as long as it runs.
Its scope is similar to the lifetime of the entire program. Moreover, the built-in namespace encompasses the global namespace, which further encompasses the local namespace.
Here is the command you can try in Python:
Here are a few examples of the built-in namespace:
2. Global Namespace
The global namespace in Python includes functions and other variables defined at the main level of a program. It is created when the main body executes and exists until the interpreter terminates.
The interpreter creates a global namespace for a module that Python loads with the import statement. If a file in Python is used as a module, the variables in that file are also imported and used accordingly.
a = 0 # global variable print(a)
3. Local Namespace
A local namespace in Python is created when a local function is invoked. It consists of all the variables and functions declared by a program. It exists until the function terminates. Objects declared in this namespace can’t be used outside the function.
def foo(): a = 10 print(a) foo() print(a)
This command shows the behaviour of a local namespace.
How to Use Namespaces in Python Programming?
There are two primary ways to work with namespaces in Python:
Modules are Python files that contain definitions and statements. They serve as namespaces by grouping related code together. You can create your own modules or use built-in or third-party modules.
To access names (variables, functions, etc.) defined in a module, you can use the dot notation.
# Importing a module import math # Accessing a name from the math module print(math.pi) # Importing a specific name from a module from math import sqrt # Accessing the imported name directly print(sqrt(9)) Using classes: Classes in Python also act as namespaces. When you define a class, the class itself becomes a namespace, and its attributes are accessible through dot notation. You can create instances of the class to access its attributes and methods. Example: # Defining a class class MyClass: x = 10 def my_method(self): print("Hello, World!") # Accessing the class attribute print(MyClass.x) # Creating an instance and accessing the method obj = MyClass() obj.my_method()
The Lifetime of a Python Namespace
The namespace lifetime depends on the scope of an object. As soon as an object ends, the lifetime of that namespace also ends. Therefore, you can’t access the inner namespace objects from an outer namespace.
What is Scope in Python?
The scopes in Python mean the region or context in which a name (variable, function, class, etc.) is defined and can be accessed. It determines the visibility and lifetime of a name within a program.
Levels of Scope in Python
Python has several levels of scope, including global scope, local scope, and nested scope.
1. Global scope:
Names defined at the top level of a module or declared as global inside a function have global scope. They can be accessed from anywhere within the module or function. Global names are accessible throughout the entire program.
# Global scope global_var = 10 def my_function(): print(global_var) print(global_var) # Output: 10 my_function() # Output: 10
2. Local scope:
Names defined inside a function have local scope and are accessible only within that function. Local names are created when the function is called and destroyed when the function completes execution. Each function call creates a new local scope.
def my_function(): local_var = 20 print(local_var) my_function() # Output: 20 print(local_var) # Error: NameError: name 'local_var' is not defined
3. Nested scope:
In Python, when you define a function inside another function, the inner function has access to names defined in the outer function's scope. This is called nested scope. The inner function can access names from its own scope, the enclosing function's scope, and the global scope.
def outer_function(): outer_var = 30 def inner_function(): print(outer_var) inner_function() # Output: 30 outer_function()
Python follows the principle of "LEGB" to resolve names in nested scopes: Local, Enclosing (non-local), Global, and Built-in.
This order determines the priority of scopes when accessing names. If a name is not found in the current scope, Python will search in the next enclosing scope, and so on, until it reaches the global and built-in scopes.
Understanding Python scope and namespaces is essential for correctly accessing and manipulating variables within your Python programs. It helps in managing variable lifetimes, avoiding naming conflicts, and writing clean and maintainable code.
Scope of Objects in Python
Several unique namespaces are defined in Python, but we might not be able to access all of them from every section of the program. That is where the concept of scope comes into the picture. It refers to the coding region of a program from which a specific Python object or namespace is easily accessible without any prefix.
So, rather than accessing a particular object from anywhere, it can be accessed by its scope in the program. For example, a variable in a function can access inside the function.
There are a minimum of three nested scopes at any given time:
Scope of the present function with local names
Scope of the module with global names
Outermost scope with built-in names
When somebody makes a reference within a function, the program searches the name in the local namespace, then in the global namespace and lastly, in the built-in namespace. In the case of a function within another function, a new scope is nested in the local scope.
Python Namespace Dictionaries
Namespaces are dictionaries with keys as object names and values as objects themselves. In Python, global and local namespaces are implemented as dictionaries. Python offers the globals() and locals() methods to allow us access to global and local namespace dictionaries.
The globals() Method
It returns a reference to the current global namespace dictionary. It is used to access objects in the global namespace.
The locals() Function
This method in Python is similar to the globals() method but allows access to objects in the local namespace.
Python Namespace vs Scope (Difference)
Here are the differences between namespaces and scope in Python in a tabular form:
A short and simple Python program will create various different objects, but in a complex program, this number can reach up to a thousand. Python namespace enables the interpreter to track these objects and their names. In this part of our full Python Tutorial, we covered everything about Python namespaces and variable scope.
If you want to learn Python in further detail and seek guidance to upskill yourself to accelerate your career growth, then go for the online Python Course with live training by industry experts.