Namespace in Python

In this tutorial, we will learn about the namespace in Python, the structure used to organize the symbolic names assigned to objects in a Python program, why namespace is important, and how we can use them in our Python program. Let's have a brief introduction to a namespace.

What is Namespace?

In Python, a way to give each object a unique name is through a namespace. Variables and methods are examples of objects in Python. To put it another way, it is a collection of the known symbolic names and the details about the thing that each name refers to. A name can be thought of as a key in a dictionary, and objects are the values in a namespace. We should figure out it with a genuine model - A namespace resembles a last name. If there are multiple "Peter" names in the class, it may be difficult to locate a "Peter" name; however, when we specifically request "Peter Warner" or "Peter Cummins," In a class, it might not be common for multiple students to have the same first and last name.

The Python interpreter can get a better understanding of the exact method or variable in the code thanks to the namespace. As a result, its name contains additional information, including Space (related to scope) and Name, which denotes a unique identifier.

In Python, there are four types of namespaces which are given below.

  • Built-in
  • Global
  • Enclosing
  • Local

As these namespace various have lifetimes, Python interpreter creates namespaces as necessary and deletes them when they are no longer needed.

Let's understand the various types of namespace in Python.

The Built-in Namespace

As its name suggests, it contains pre-defined names of all of Python's built-in objects already available in Python. Let's list these names with the following command.

Open the Python terminal and type the following command.

Command -

Output:

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 
'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 
'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

The built-in namespace creates by the Python interpreter when its starts up. These are terminated when Python interpreter terminates.

The Global Namespace

The global namespace consists of any names in Python at any level of the main program. It is created when the main body executes and remains in existence until the interpreter terminates.

The Python interpreter creates a global namespace for any module that our Python loads with the import statement. To get more information, visit our Python Module.

The Local and Enclosing Namespaces

The local namespaces are used by the function; When the function is run, the Python interpreter creates a new namespace. The local namespaces continue to exist after the function has finished running. The capability can likewise comprise of another capability. As shown below, we can define one function within another.

Example -

In the above model, the capability g() is characterized inside the collection of f(). We called the g() function within the f() and the main f() function. Let's look at how the above function works:

  • Python creates a new namespace for f() when we call it.
  • Likewise, the f() calls g(), g() gets its own different namespace.
  • The local namespace g() was created for the enclosing namespace, f().

Each of these namespaces is terminated when the function is terminated.

Scope of the Object/Variable

The term "scope" specifies which coding region of a particular Python object can be accessed. Every object and variable has a scope in the program from which we can access that variable. For instance, a function variable can only be accessed within the function. Let's examine the following illustration:

Example -

Output:

Inside scope_func
Inside inner function, value of var: 20
Traceback (most recent call last):
  File "d:/Python Project/listproblems.py", line 343, in 
    scope_func()
  File "d:/Python Project/listproblems.py", line 342, in scope_func
    print("Try printing var from outer function: ",var)
NameError: name 'var' is not defined

Python Namespace Dictionaries

In the previous tutorial, we talked about how namespaces are like dictionaries, with keys representing object names and values representing actual objects. As dictionaries, Python uses both global and local namespaces. Access to global and local namespace dictionaries is made possible by Python's globals() and locals() methods.

The globals() Method

The globals() method returns a reference to the current global namespace dictionary. We can use it to access the objects in the global namespace. Let's see the below example.

Example -

As we can see that, there are many built-in entries in globals() method. It may be differ according to your operating system and Python version. Now let's define the global variable and observe the differences.

After the assignment of a = 20, a new global variable assigned to the global namespace dictionary. We can access the values as we access in the dictionaries. Let's see the below example.

We can modify the dictionary value using the globals() function.

Now the new value of a will be appeared in the global dictionaries.

The locals() Function

Python also provides the locals() method similar to globals() but accesses objects in the local namespace instead. Let's see the following example.

Example -

When we call the func(10, 20), the locals() return the dictionary representing the function's local namespace. In the function scope, we defined the local variable str1; the local namespace included the function arguments since they are local to the func().

Notwithstanding, when we call local people() capability, it acts equivalent to the globals() capability. The globals() function and the locals() function differ slightly. The globals() function not only defines additional variables but also stores the return value. The dictionary will contain the new variables and their values. Take a look at the example below.

Example -

Here the glob_var is a reference to the global namespace dictionary. The new assignment statements x and y appeared in the glob_var dictionary.

Changing Variables Out of Scope

In the calling environment, the function can change the argument by passing a different value, but sometimes it can't change the value.

An immutable argument cannot be modified by a function.

A mutable argument can be changed in place, but it cannot be completely redefined.

Let's understand the following scenario.

Example -

Output:

40
20

We define a global variable x = 20 and also in function with the same name. When the func() execute, it creates the new local variable reference to an integer object whose value is 40. Inside the func() body, the assignment statement won't affect the global object.

However, a function can modify an object of a mutable type outside its local scope. Let's understand the below example.

Example -

The my_list is a list and it is mutable type. The func() can modify inside my_list even though its outside the local scope. But, if we try to reassigned the my_list, it will create the new local object and won't modify the global my_list. Let's see the below example.

Example -

Output:

['A', 'B', 'C', 'D', 'E']

Conclusion

We take care of the namespace, how we can utilize it, and the variable's degree. Numerous distinct objects can be created with a brief Python program. This number may exceed one thousand in a complicated Python program. The Python namespace makes it easier for the interpreter to remember these objects' names.






Latest Courses