In Python, a namespace is a dictionary that binds names to objects. The levels of namespaces are local, global, and built-in. Modules are separate namespaces for organizing code. When importing, Python creates a new namespace for each module.
import module — imports the module and access objects through module.name.from module import name — imports an object from the module directly into the current namespace (risk of name conflicts).as — allows you to set an alias.To avoid name conflicts:
import mymodule), not asterisks (from... import *).__init__.py).import module as m).project/
package/
__init__.py
module1.py
module2.py
import package.module1 from package.module2 import function as fn
Question: What happens if you import a module twice? Will the entire module's code run again?
Answer: No. During the first import, the module is executed and the result is cached in sys.modules. A repeated import returns the already loaded module object, and its code is not executed again.
# module.py print('Hello!') # main.py import module # prints Hello! import module # prints nothing
Story
from settings import * in several modules, resulting in local variables being unexpectedly "overwritten" when settings were changed, causing hard-to-detect bugs.Story
utils.py). During integration, the "identical" named modules "overrode" each other, leading to unexpected behavior and complex bugs.Story
In one of the libraries, they tried to "hot-reload" the module with new settings using importlib.reload. They did not take into account that already imported other modules retained old references to the objects, causing changes not to be applied throughout the application.