Core Python·Lesson 13 of 67·intermediate
Modules, packages and virtual environments
Split a script into files that import each other, understand how Python finds them, and pin an environment so your results reproduce on someone else's machine.
In this lesson · 18 min
- →Import from the standard library and from your own files
- →Write a module and a package, and import from both
- →Explain how Python finds a module, and why a file named random.py breaks everything
- →Guard script-only code with the main check
- →Create a virtual environment and pin dependencies so a run reproduces
A script becomes software when it stops being one file. Modules are how Python splits code up, and environments are how you make sure the code that ran on your laptop runs on the machine that trains the model.
Importing
import x keeps the module’s namespace, so you write x.thing and a reader knows where thing
came from. from x import thing is shorter at every use site. Prefer the second for a handful of
well-known names, the first when the module name adds clarity.
Your own modules
A module is just a .py file. Python’s virtual filesystem is available here, so you can write
one and import it in the same program:
Everything defined at the top level of that file — constants, functions, classes — becomes an attribute of the module object.
A module runs once
The first import executes the file top to bottom. Every later import of the same name reuses
the module object already in sys.modules:
That is why import-time work is dangerous: a module that opens a connection or loads a 2 GB checkpoint at the top level does it the moment anything imports it, including your test suite.
The main check
A file can be imported and run directly. The difference is the __name__ variable: it is
"__main__" when the file is the program, and the module’s name when it has been imported.
Put everything a script does behind if __name__ == "__main__": and everything it offers
above the guard. Then the same file is both a command-line tool and an importable library.
Packages
A package is a directory of modules. An __init__.py file makes it importable as one unit, and
is the natural place to decide what the package exposes:
The leading dot in from .chunking import split is a relative import — “the chunking
module next to me”. Use relative imports inside a package and absolute imports everywhere else.
How Python finds a module
sys.path is searched in order, and the first match wins:
Because the directory of your script comes first, a file of your own called random.py or
json.py shadows the standard library module of that name — and the error it produces points
somewhere else entirely:
A program that started from that directory would import the empty file, and every later
random.randint(...) would fail with AttributeError: module 'random' has no attribute 'randint' — pointing at a line that has nothing wrong with it.
Virtual environments
Installing packages system-wide means every project shares one set of versions, and two projects eventually want different ones. A virtual environment is a private directory of packages for one project.
These commands run on your own machine, not in this page:
python -m venv .venv # create it
source .venv/bin/activate # activate it (Linux/macOS)
.venv\Scripts\activate # activate it (Windows)
pip install numpy pandas scikit-learn
pip list # what is installed
deactivate # leave it
Once active, python and pip refer to the environment’s copies. .venv/ is generated, so it
belongs in .gitignore, never in a commit.
Pinning what you installed
Recording versions is what makes a run repeatable:
pip freeze > requirements.txt # exact versions of everything installed
pip install -r requirements.txt # recreate that environment elsewhere
A modern project declares its dependencies in pyproject.toml instead, separating what you
depend on from what happened to get installed:
[project]
name = "rag-service"
requires-python = ">=3.11"
dependencies = [
"anthropic>=0.40,<1.0",
"numpy>=2.0",
"pydantic>=2.7",
]
[project.optional-dependencies]
dev = ["pytest>=8.0", "mypy>=1.10"]
Try it yourself
Write a module tokens.py that defines count(text) returning the number of whitespace-separated words, then import it and print count: N for the sample text.
Move the script body of report.py behind a main check, so importing it prints nothing but summarise is still available.
Check yourself
You add a file called json.py to your project, and an unrelated import of the standard library json starts failing. Why?
Check yourself
What does if __name__ == '__main__': achieve in a file that is both a tool and a library?
Recap
import xkeeps the namespace;from x import yis shorter. Neverimport *.- A module is a
.pyfile; its top-level names become attributes. A package is a directory with an__init__.pythat decides what the package exposes. - A module’s body runs once, on first import — so avoid expensive work at import time.
__name__is"__main__"only when the file is the program. Guard script behaviour with it.sys.pathis searched in order and your own directory comes first, so never name a file after a standard library module.- A virtual environment isolates a project’s packages; pinned versions in
requirements.txtorpyproject.tomlare what make a result reproducible.