When a module is imported in Python, the interpreter searches for it in the directories listed in sys.path. It first looks among standard modules, then among .py, .pyc files, and directories containing a __init__.py file (packages).
sys.modules.ModuleNotFoundError exception will be raised..pyc) and cached (if there are write permissions).# mypkg/__init__.py (can be empty) # mypkg/mod.py # main.py import mypkg.mod
__init__.py (mandatory for Python <3.3) all matter.sys.path directories (the current script's directory always comes first).from . import ..., absolute/relative import).What happens if there is a file named
random.pyin the same directory as your script and you try to import the standard modulerandom?
Your local file random.py will be imported, not the standard library. A common cause of hard-to-detect bugs is naming collisions with library modules (shadowing). Care should be taken when naming files.
Story
In a large project, the module email.py accidentally overshadowed the standard email module from the library, and developers struggled for a long time to understand why the email parsing functions from third-party libraries were not working.
Story
In an ML project, the os.path function didn’t work: there was a file named os.py next to the main script that intercepted all calls to the standard module. They spent a month debugging until they found the naming conflict.
Story
In a microservices REST API, cyclical imports occurred when trying to make relative imports of models between several sub-packages. They resolved the issue only after refactoring the project structure and establishing a clear module loading order.