01.06

Modules, packages, and imports

skillmaxingPython with AIModules, packages, and imports
Visual lesson

Modules, packages, and imports

Included with Pro · 4:08
Lessons · 1,012 words

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.

What import does
Figure 1What import doesThe first import runs the file; every later one is a dictionary lookup.

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.

Pro

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.

Unlock full access to
Python with AIAI researchComplete system design
30% off with LAUNCH30ends in 7h 40m
Buy now
View all plans ·Already Pro? Sign in
124 online