top of page
Writer's pictureThe Tech Platform

Introduction to Namespace in Python

A namespace is a system that has a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary. Let’s go through an example, a directory-file system structure in computers. Needless to say, that one can have multiple directories having a file with the same name inside every directory. But one can get directed to the file, one wishes, just by specifying the absolute path to the file.


The namespace helps the Python interpreter to understand what exact method or variable is trying to point out in the code. So its name gives more information - Name (which means name, a unique identifier) + Space (related to scope).



Types of Namespace in Python:



Built-in Namespace

A built-in namespace contains the names of built-in functions and objects. It is created while starting the python interpreter, exists as long as the interpreter runs, and is destroyed when we close the interpreter. It contains the names of built-in data types,exceptions and functions like print() and input(). We can access all the names defined in the built-in namespace as follows.

builtin_names = dir(__builtins__)
for name in builtin_names:
    print(name)

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.


Global Namespace

Global namespaces are defined at the program or module level. It contains the names of objects defined in a module or the main program. A global namespace is created when the program starts and exists until the program is terminated by the python interpreter. The concept of a global namespace can be understood from the following example.

myNum1 = 10
myNum2 = 10


def add(num1, num2):
    temp = num1 + num2
    return temp

In the example above, myNum1 and myNum2 are in the global namespace of the program.


Local Namespaces

The function uses the local namespaces; the Python interpreter creates a new namespace when the function is executed. The local namespaces remain in existence until the function terminates. The function can also consist of another function. We can define one function inside another as below.


Example -

myNum1 = 10
myNum2 = 10


def add(num1, num2):
    temp = num1 + num2
    return temp

Here, the variable names num1, num2 and temp are defined in the local namespace in the function add.


Enclosing namespace

As we know that we can define a block of code or a function inside another block of code or function, A function or a block of code defined inside any function can access the namespace of the outer function or block of code. Hence the outer namespace is termed as enclosing namespace for the namespace of the inner function or block of code. This will be more clear from the following example.

myNum1 = 10
myNum2 = 10


def add(num1, num2):
    temp = num1 + num2

    def print_sum():
        print(temp)

    return temp

In the above example, the local namespace of add() function is the enclosing namespace of the print_sum() function as print_sum() is defined inside the add() function.



Python Namespace Method:

Python comes with the globals() and locals() methods that allow us to access global and local namespace dictionaries.


1. 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 -

>>> type(globals())  
<class 'dict'>  
>>> globals()  
{
    '__name__': '__main__', 
    '__doc__': None, 
    '__package__': None, 
    '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 
    '__spec__': None, 
    '__annotations__': {}, 
    '__builtins__': <module 'builtins' (built-in)>
}  

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.

>>> a = 20  
>>> globals()  
{
    '__name__': '__main__', 
    '__doc__': None, 
    '__package__': None, 
    '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 
    '__spec__': None, 
    '__annotations__': {}, 
    '__builtins__': <module 'builtins' (built-in)>, 
    'a': 20
}  

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.

>>> a = 20  
>>> globals()  
{
    '__name__': '__main__', 
    '__doc__': None, 
    '__package__': None, 
    '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 
    '__spec__': None, 
    '__annotations__': {}, 
    '__builtins__': <module 'builtins' (built-in)>, 
    'a': 20
}  
>>> a  
20  
>>> globals()['a']  
20  

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

>>> globals()['a'] = 100   
>>> a  
100  

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


2. 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 -

>>> def func(a, b):  
...     str1 = "Hello"  
...     loc = locals()  
...     print(loc)  
...   
>>> func(10, 20)  
{'a': 10, 'b': 20, 'str1': 'Hello'}  

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().


However, when we call the locals() function, it behaves the same as the globals() function. There is a small difference between globals() and locals() function. The globals() save the return value and subsequently define additional variables. The new variables will show up in the dictionary along with their value. Let's see the below example.


Example -

>>> glob_var = globals()  
>>> glob_var  
{
    '__name__': '__main__', 
    '__doc__': None, 
    '__package__': None, 
    '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 
    '__spec__': None, 
    '__annotations__': {}, 
    '__builtins__': <module 'builtins' (built-in)>, 
    'a': 100, 'func': <function func at 0x000001670FB85160>, 
    'glob_var': {...}, 
    'x': 100, 'y': 'JavaTpoint'
}  

>>> x = 100    
>>> glob_var  
{
    '__name__': '__main__', 
    '__doc__': None, 
    '__package__': None, 
    '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 
    '__spec__': None, 
    '__annotations__': {}, 
    '__builtins__': <module 'builtins' (built-in)>, 
    'a': 100, 'func': <function func at 0x000001670FB85160>, 
    'glob_var': {...}, 
    'x': 100, 
    'y': 'JavaTpoint'
}  

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.




The Tech Platform

0 comments

Recent Posts

See All

留言


bottom of page