Python Namespace
In python, the namespace is a very important concept that should be understood before using any function or variables.
When we write code, we often use variables, libraries, functions, modules, etc. So there could be a situation where the function name you are using could already be the name of another function or another variable. In that case, we can get errors, and our program will not work as we want it to. In these situations, we should know how the python program works with these functions, variables, and methods. This is where the concept of namespace comes into the picture.
A namespace provides a unique name to each object in python. Python revolves around the concept of objects, which can be a variable or a method. A namespace is like a dictionary where the name represents a key, and the object represents the value of the key. If we break the namespace, then we will use the name as a unique identity, and space is used as the scope where it is used. In python, the name might be a variable, a method, or a function, whereas the space is the location where we are trying to access those variables.
Let’s understand this concept with an example, we have a list of student names, and we have to find a particular student from that list. Now in this situation, a namespace is like a surname. We can have multiple ‘Alex’ in the list, so it is hard to find the one we are looking for just by the name, but if we know the surname too, then it will be easy to find the exact student. Let’s say we are looking for ‘Alex Rosh’ (with surname). We are using the complete name. This way, it will be very easy to find the student because there can’t have too many students with the same name and surname.
Types of Namespace
- Built-in namespace
- Global namespace
- Local namespace
- Enclosing namespace
Let’s understand these namespaces in brief. The built-in namespace encloses the global namespace and the global namespace encloses the local namespace.
- Built-in Namespace
In the hierarchy of namespace, a built-in namespace is the highest level of the namespace. It can be very useful for finding the default names in python libraries. It contains pre-defined names of all python objects. We can find these names using the following command on the python terminal.
Command
>>dir(__builtins__)
Output
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', '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', 'aiter', 'all', 'anext', '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']
- Global Namespace
In this namespace, we consider any name in python at any level of the main program. It is created when we create the program and ends until it terminates. We create a global namespace for any module in python using the import statement.
- Local Namespace
In this namespace, we consider any name that comes under a function. It is created inside a function and ends once we exit the function. In the other words, it is created once the function is called and the scope ends when we return the function.
- Enclosing Namespace
In this namespace, we consider any name that is defined inside a nested function. A nested function is a function that is defined inside another function. In other words, a function inside a function. Its lifecycle is similar to the local namespace.
Let’s understand the later three namespaces using an example.
Code
# x in in the global namespace
x = 5
def some_func():
# y is in the local namespace
y = 6
def some_inner_func():
# z is in the nested local namespace or enclosing namespace
z = 7