Level: Intermediate | Prerequisite: Week 2
Learning Goals
- Create your own modules and import them
- Know the
__name__ == "__main__"pattern - Understand package structure and the role of
__init__.py - Install external packages using
pip
1. Module
A .py file is a module. Use import to use it in another file.
# calc.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
# main.py
import calc
print(calc.add(3, 5))
from calc import add, sub
print(add(1, 2), sub(5, 3))
from calc import add as plus
print(plus(10, 20))
2. __name__ == "__main__"
Code that only runs when executed directly as a script.
# mymod.py
def main():
print("Executed")
if __name__ == "__main__":
main()
Thanks to this pattern, even if you import mymod, main() does not run automatically.
3. Package
A folder that bundles multiple modules together. Must have __init__.py to be recognized as a package (not required from Python 3.3+).
mypkg/
├── __init__.py
├── math_utils.py
└── string_utils.py
#use
from mypkg.math_utils import add
from mypkg.string_utils import slugify
4. Using __init__.py
# mypkg/__init__.py
from .math_utils import add, sub
from .string_utils import slugify
This way, from mypkg import add is possible (convenient).
5. Installing external packages with pip
pip install requests
pip install requests==2.31.0 #Specific version
pip install -r requirements.txt #Batch installation
pip list #Installed list
Key Examples (examples/)
| File | Content |
|---|---|
calc.py |
Custom module |
main.py |
Uses calc module import |
mypkg/__init__.py, math_utils.py, string_utils.py |
Package |
use_pkg.py |
Using package |
⚠️ Common Mistakes
- Circular import — A imports B, B imports A → ImportError
- Incorrect relative import — Inside a package, use
from .module import ... - Module name conflicts with standard library — Creating a file named
random.pywill override the standard random
❓ FAQ
Q1. Which should I use, import or from?
A. If you use only 1-2 functions, use from; if there are many or you want to specify the module name, use import.
Q2. pip is not installed
A. Check with python -m ensurepip or python -m pip --version.
Q3. Why use a virtual environment (venv)? A. To separate library versions for each project. Almost essential for the next semester and in practice.
📝 Exercises (exercises/)
exercise1.md—calculator/package (basic + advanced)exercise2.md—string_utils.py(slugify, truncate)- Using
exercise3.md—__name__ == "__main__"
Next Week
Week 4. Standard Library