What happens if I import an module or function that conflicts with an object defined in my local namespace?


#1

Question

In the context of this exercise, what happens if I import a module or function that conflicts with the name of an object defined in my local namespace?

Answer

If you import a module or function that conflicts with the name of an object defined in your local namespace, then the object defined in your local namespace will overwrite the one that was imported. However, it will only overwrite if the object in your namespace is defined after the import statement in the code.

Example

from math import sqrt

print(sqrt(4)) # 2.0

# Defining it after the import statement will
# overwrite the function with the same name
def sqrt(n):
  return n * 100

print(sqrt(4)) # 400

If the conflict is with the module, you can avoid this by aliasing it to another name. To avoid function name conflicts, it is best to be aware of all the function names from the module and to name your local namespace functions differently.