Why are they used in python?
A simple way to put it is that when you are writing a 100,000-lines program, it is impossible to choose different names for all variables. So, every function defines a namespace. It is like a box with bindings (variables) inside, and the variables cannot be accessed from the outside.
>>> def f(x):
... a = x + 2
... print(a)
...
>>> f(5)
7
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
Modules are also namespaces. There is not a single sqrt
function for example. The one from math
applies to floats. The one from cmath
also handles complex number. Thanks to namespaces, there is no conflict between these functions. They are called math.sqrt
and so on.
Furthermore, you will discover when you learn object-oriented programming that objects are namespaces too. A simple example is file objects:
>>> file = open("foo")
>>> file.name
'foo'
>>> file.closed
False
>>> file.mode
'r'
>>> file.encoding
'UTF-8'
See? This file object has associated data, which it owns. The object is a form of namespace.
You can read a lot on the net about namespaces, like
https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces
https://www.programiz.com/python-programming/namespace