Modules & Imports
- Import from the standard library with
import - Import specific names with
from ... import ... - Organize your own code into reusable modules
- Understand
__name__ == "__main__"for scripts vs libraries
Circular imports and misuse of __name__ == "__main__" are the top reasons Django and Flask apps fail to boot. Understanding sys.path, package __init__.py, and relative imports is what makes monorepos and installable packages actually work.
- Circular imports from top-level
from x import y— defer imports into function bodies or restructure modules. - Running
python module.pyinside a package — relative imports break; usepython -m package.module. - Shadowing stdlib names like
email.pyortypes.pyin your project — silently breaks unrelated imports.
A module is just a .py file. A package is a folder with an __init__.py.
Four import shapes
import math— use asmath.piimport math as m— aliasfrom math import pi— pull a name into your namespacefrom math import pi as PI— pull and alias
Where Python looks
- Built-ins → 2. The current file's directory → 3. Installed site-packages → 4.
sys.path
Try it
- Try
from collections import defaultdict— build one. - Import
randomand generate 5 random ints between 1 and 100.
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Use
importlib.import_moduleto load the'math'module dynamically, then printmath.pirounded to 4 decimal places. Expected output:3.1416. - Exercise 2
Use the older
__import__builtin to load the'json'module, then use it to serialize the dict{'a': 1, 'b': 2}to a JSON string and print the result. - Exercise 3
Every imported module is cached in
sys.modules. Importos, then verify that'os' in sys.modulesAND thatsys.modules['os'] is os. PrintTrueif both are true.