Modules, packages, and imports
Modules, packages, and imports
A module is a .py file. Importing it runs the file, top to bottom, exactly once per process, and stores the resulting namespace in sys.modules so every later import gets the same object. A package is a directory containing modules and an __init__.py. That is the whole model: no build step, no linker, no manifest of exports. Everything a file defines at the top level is importable, and everything it does at the top level happens at import time.
The consequences are simple but easy to trip over. Code at module level runs on import, so a module that opens a database connection when imported has just made every test that imports it need a database. Two modules that import each other can find each other half-initialised. And Python has to find the file, which depends on where the process started. This lesson gives Relay its package structure and shows the three or four rules that keep imports boring.
Continue reading
Pro unlocks every video lesson, the full notes and runnable code across the Python with AI course, from the language itself to agents, MCP, Langfuse and deployment.