Real projects span many files and lean on third-party libraries. This chapter is how Python code is organised and shared: splitting code into modules and packages, importing it cleanly, and — crucially — using virtual environments so each project has its own isolated set of dependencies.
Modules
A module is simply a .py file. Any names defined in it (functions, classes, variables) can be imported into another file:
# calc.pyPI = 3.14159def area(r):return PI * r * r# app.pyimport calcprint(calc.area(2)) # 12.566…print(calc.PI)
Import styles
| Import | Use |
|---|---|
import calc | Access as calc.area — clear namespacing |
from calc import area | Use area directly |
from calc import area as a | Rename on import |
import numpy as np | The conventional alias pattern |
Packages
A package is a folder of modules. Group related modules into a directory and import with dotted paths — this is how every library you install is structured:
myapp/__init__.py # marks the folder as a packagemodels.pyutils/__init__.pytext.py# import from itfrom myapp.models import Studentfrom myapp.utils.text import clean
The __main__ guard
When Python imports a module it runs the whole file. To keep code that should only run when the file is executed directly (not when imported), put it under the __name__ == "__main__" guard:
def main():print("running the app")if __name__ == "__main__":main() # runs on 'python app.py' — but NOT on 'import app'
pip & virtual environments
pip installs third-party packages from PyPI. But installing everything globally means two projects can't need different versions of the same library. A virtual environment is a per-project, isolated set of packages — the professional default:
python -m venv .venv # create an environment in .venv/source .venv/bin/activate # activate (macOS/Linux).venv\Scripts\activate # activate (Windows)pip install pandas requests # installs into THIS project onlypip freeze > requirements.txt # record exact versionspip install -r requirements.txt # reproduce elsewhere
Practice
Split a small script into two modules (a helpers.py and an app.py that imports it), add a __main__ guard, create a virtual environment, install a library into it, and freeze a requirements.txt.
Key takeaways
- 01A module is a .py file; import its names into other files.
- 02Prefer explicit imports (import x / from x import y) over from x import *.
- 03A package is a folder of modules with __init__.py, imported by dotted path.
- 04Guard direct-run code with if __name__ == "__main__".
- 05Use a virtual environment per project (python -m venv), install with pip, and commit requirements.txt (not .venv/).
