Python Tutorial 0/52 lessons ~6 min read Lesson 29
Modules & Imports
A module is a .py file.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
A module is a .py file. A package is a directory with __init__.py. import caches modules in sys.modules.
Understanding the topic
Core concepts to understand:
import math— namespace import.from math import sqrt— specific import.- Absolute vs relative imports.
if __name__ == '__main__':for scripts.
Syntax reference
Visual flow / code:
python
# project/utils/math.pydef square(x): return x * x# project/main.pyfrom utils.math import squarefrom utils import math as Mprint(square(5))print(M.square(6))if __name__ == "__main__":print("Run as script")
Execution workflow
1Modules & Imports Workflow
1 / 4Step 1
import math — namespace import.
Apply this step while implementing modules & imports in real code.
Real-world use
Modern packaging uses src/ layout + pyproject.toml. Avoid from x import * — explicit imports beat magic.
Best practices
- Prefer absolute imports.
- Never
import *in production code. - One responsibility per module.
Common mistakes
- Circular imports — split shared types into a separate module.
Hands-on exercise
Interview preparation — practice these questions:
- __name__ == '__main__' — why?
- Absolute vs relative import?
- What's sys.modules?
Summary
In summary: File = module; dir = package. Explicit imports always.
Ready to mark this lesson complete?Track your journey across the entire course.