A namespace is basically a system to make sure that all the names in a program are unique and can be used without any conflict. You might already know that everything in Python—like strings, lists, functions, etc.—is an object. Another interesting fact is that Python implements namespaces as dictionaries. There is a name-to-object mapping, with the names as keys and the objects as values. Multiple namespaces can use the same name and map it to a different object. Here are a few examples of namespaces:
- Local Namespace: This namespace includes local names inside a function. This namespace is created when a function is called, and it only lasts until the function returns.
- Global Namespace: This namespace includes names from various imported modules that you are using in a project. It is created when the module is included in the project, and it lasts until the script ends.
- Built-in Namespace: This namespace includes built-in functions and built-in exception names.
For example, the math and cmath modules have a lot of functions that are common to both of them, like
exp(), etc. If you are using both of these modules in the same program, the only way to use these functions unambiguously is to prefix them with the name of the module, like