- A namespace is a container that provides a named context for a set of identifiers.
- It helps programs avoid potential name clashes by associating each identifier with the namespace from which it originates.
- A name clash occurs when two otherwise distinct entities with the same name become part of the same scope.
- In Python, name clashes can happen if two or more modules contain identifiers with the same name and are imported into the same program.
Example:
- In the example,
module1
andmodule2
are imported into the same program. - Each module contains an identifier named
double
, which returns very different results. - When the function call
double(4)
is executed in the main program, a name clash occurs because it cannot be determined whichdouble
function should be called.
# module1.py
def double(x):
return x * 2
# module2.py
def double(x):
return x ** 2
- In the example,
module1
andmodule2
are imported into the same program. - Each module contains an identifier named
double
, which returns very different results.
result1 = double(4)
result2 = double(4)
- When the function call
double(
4)_ is executed in the main program, a name clash occurs because it cannot be determined whichdouble
function should be called.
- Namespaces provide a means for resolving name clash problems.
- Each module in Python has its own namespace, including the names of all items in the module (functions, global variables, etc.).
- To distinguish between identifiers with the same name in different modules, they are fully qualified with the name of the module in which each is defined.
Example with Resolution:
result1 = module1.double(4)
result2 = module2.double(4)
- When both modules are imported into the main script, calling
module1.double(4)
executes the function frommodule1
while callingmodule2.double(4)
executes the function frommodule2