What is namespace in Python
A Namespace is associated with the scope. In Python, a namespace is a system to have a unique name for every object, in order to avoid ambiguity among objects. An object can be a variable or a method. Python implements the namespace using a Python dictionary, that is, a mapping from names (keys) to objects (values).
Types of namespaces:
The built-in namespace includes global namespace and global namespace contains local namespace
- built-in names: this namespace contains built-in functions (e.g. abs(), cmp(), …) and built-in exception names
- global names of a module
- local names in a function or method invocation
Lifetime of a Namespace:
The lifetime of a namespace depends upon the scope of objects.
If the scope of an object comes to an end, then the lifetime of that namespace also ends. The lifetimes of namespaces may differ since they are created at different points in time.
The built-in namespace is created when the Python interpreter starts up and it never gets deleted.
The global namespace of a module is created while the module is read. It will last until the interpreter quits.
A local namespace is formed when a function is called. It will get deleted unless the function ends or if the function raises an exception
Scope:
The region of a program where a namespace can be directly accessed is known as the scope.