Lesson · Modules, Packages & Imports
Modules
55 min readModules
A module is a Python file loaded into its own namespace. Imports are executable operations, so module design must consider public names, side effects, and initialization order.
Learning goals
- Explain an import as an executable operation: locate, run, cache, bind.
- Predict what
import mathbinds in the importing namespace versus whatfrom statistics import meanbinds. - Trace the difference between a module's own namespace and the namespace of the file that imports it.
- Explain when top-level module code runs and why import-time side effects deserve suspicion.
- Read
__name__in both invocation modes and write a correct__main__guard.
Mental model
The four steps explain the two behaviors people find surprising: the body runs only once per process because the cache holds the finished module object, and everything the body does at top level (prints, file reads, network calls) happens during that first import. The name you get is either the module itself or, with from ... import ..., a single member pulled out of it.
Mental model
read it top to bottom
import math ↓ locate: find the source file or an already-cached module ↓ execute: run the module body once, on the first import ↓ cache: store the finished module object in sys.modules ↓ bind: make a name available in the importing namespace
Core idea
An import is a small program the interpreter runs on your behalf: find the module, execute its body once, remember the result in sys.modules, and bind a name in the current namespace. That explains the two behaviors people find surprising: running an import twice in one process never reruns the body, and any top-level statement is a side effect that fires during import. Choosing between import x and from x import y is mostly about what appears in your namespace and how visible the origin of each name stays.
What a module is
A module is a runtime object that usually corresponds to one Python source file and owns a global namespace. Importing creates or retrieves that module object.
import x
import x loads or retrieves module x and binds the top-level module name in the current namespace. Access members through the module object to keep provenance clear.
from x import y
from x import y loads module x, then binds attribute y directly in the importing namespace. This can be concise but makes name origin less visible.
Aliases
An alias is an extra name given to an imported object: import math as m binds m, and from statistics import mean as average binds average to the function. The alias is an ordinary name binding in the importing namespace; the module or function keeps its original name everywhere else.
Module namespaces
Each loaded module has its own global namespace stored in the module object's dictionary. Imported names and top-level assignments populate that namespace.
Module-level execution
Top-level module statements execute during the module's initial load. Keep expensive work and irreversible side effects out of import time unless initialization truly requires them.
__name__
__name__ is a string attribute every module holds: it is "__main__" when the file runs as the program entry point, and the module's import name when the file is imported. It is the attribute that the if __name__ == "__main__": guard tests.
Walkthrough
import mathbinds the namemathto the module object;math.sqrt(81)reaches the function through it and prints9.0.from statistics import mean as averageloads thestatisticsmodule on first use, pulls themeanfunction out of its namespace, and binds it locally asaverage, soaverage([10, 20, 30])prints20.print(math.__name__)reads the module's own name attribute and printsmath, the import name rather than any file path.- Predict before running: the two computed numbers and the exact string printed by
math.__name__.
Experiments to try
- Print
math.__name__afterimport math as m; confirm the alias changes the local name but not the module's own__name__. - Run
import mathtwice and compareid(math)across the two imports; explain the result using the module cache. - Check
"sqrt" in dir()before and afterfrom math import sqrt, then check"sqrt" in dir(math); state which namespace each binding lives in. - Write a small local module with a top-level
print, import it twice in one session, and count how many times the message appears.
Common mistakes
- Expecting the module body to rerun on every import: the second import finds the finished object in
sys.modulesand skips execution, which is why module-level state persists across importers. - Putting slow or irreversible work at module top level: any importer pays the cost, and a failure surfaces as an error at an unrelated call site rather than where the work lives.
- Assuming
from x import ytracks later changes: the binding copies the current object, so if the source module rebindsy, the importer keeps the old one. - Shadowing a standard-library module with a local file of the same name, for example a project-local
random.py: the import system finds the project file first, so every laterimport randomin that process loads the wrong module.
Practice: Easy
- Run the worked example and record all three lines; then add
sqrt(16)afterfrom math import sqrtand explain which namespacesqrtlives in. - Import the same standard module twice and compare
id(); state what the cache returned the second time. - Print
dir()before and afterfrom math import piand list exactly which new names appeared.
Practice: Medium
- Create
greetings.pywith ahello()function and one top-levelprint; import it from a second file and report the print order, then import it again and explain why the message does not repeat. - Write the same import three ways (
import statistics,import statistics as stats,from statistics import mean) and print the same value through each; note what each version adds to the importing namespace. - Give a module both a constant and a function that reads it; rebind the constant after importing the function with
from ... import ...and determine which value the function uses.
Practice: Hard
- Build two modules that import each other only inside functions rather than at top level; document why the top-level mutual import can fail and what the function-level version changes.
- Write a module whose top level opens a resource (a file or a timer) and move that work behind a guarded
main(); test bothpython module.pyandimport moduleand compare what runs. - Inspect
sys.modulesafter a series of imports, including one that fails with an exception, and report what the failed import leaves behind in the cache.
Lesson checklist
- I can describe the four steps of an import and say what
sys.modulescaches. - I can predict which names
import xandfrom x import yadd to the importing namespace. - I can explain why a module body runs once per process.
- I can keep import-time side effects behind a guard or a function.
Remember
An import locates a module, executes its body once, caches the module object, and binds a name in the importing namespace. That sequence explains the rules: repeated imports are cheap and quiet, top-level statements are import-time side effects, and `from x import y` copies a single name while `import x` keeps every member reachable through the module. Design modules with those consequences in mind: quiet at import time, explicit about what is public.
Interview angles
What is the main purpose of **What a module is**?+
A module is a runtime object that usually corresponds to one Python source file and owns a global namespace. Importing creates or retrieves that module object.
What should you pay attention to when using **import x**?+
import x loads or retrieves module x and binds the top-level module name in the current namespace. Access members through the module object to keep provenance clear.
How does **from x import y** fit into this lesson?+
from x import y loads module x, then binds attribute y directly in the importing namespace. This can be concise but makes name origin less visible.
Why does a top-level `print` or a slow setup call in a module cause surprises?+
Top-level statements run exactly once, during the first import, wherever that happens first in the process. The print therefore appears at an unpredictable call site and the slow work delays an unrelated operation; move such work behind a function or the __main__ guard.