Modules, Packages & Environments with uv
ModuleNotFoundError: No module named 'numpy'. Or it runs, but prints different numbers because their copy of a library is older than yours. This lesson fixes both problems: how to split your own code into files you can import, and how to give every project its own environment so the code runs the same everywhere.After this lesson, you will be able to:
- Import modules and packages with import and from...import, and write a module of your own
- Explain what the if __name__ == '__main__' guard does and why a module needs it
- Create an environment with uv venv and install packages into it with uv pip install
- Start a project with uv init, add packages with uv add, and rebuild it elsewhere with uv sync from pyproject.toml and uv.lock
- Translate the pip, venv and requirements.txt commands in an unfamiliar README into uv commands
Before you start
#The Problem: It Works on My Machine
main.py, that you wrote on your laptop:import numpy as np
features = np.array([[1.0, 2.0], [3.0, 4.0]])
print("mean per column:", features.mean(axis=0))mean per column: [2. 3.]. Your friend copies the file to a new folder and runs it with a fresh Python. This is the real result of that situation:$ python main.py
Traceback (most recent call last):
File ".../main.py", line 1, in <module>
import numpy as np
ModuleNotFoundError: No module named 'numpy'
numpy is not part of Python. It is a third-party package, which means somebody else wrote it and published it on PyPI, the Python Package Index, the public shelf where such packages live. Python only ships with the standard library (math, random, json and many more). Everything else has to be installed first.Installing it carelessly creates a second problem. If every project installs into the same place, two projects that need different versions of one library fight over it, and the second install silently replaces the first. You will watch that happen later in this lesson.
venv and pip tools, and a later section shows both side by side, because most of the instructions you will read online still use them.First, though, the other half of the lesson: your own code.
#What Is a Module?
.py file. When you import it, Python runs the file once and gives you its functions, classes and variables under the module's name.Python's standard library is a large set of modules that arrive with the interpreter. Nothing needs installing:
import math
from statistics import mean
import datetime as dt
losses = [0.9, 0.5, 0.31, 0.22]
print(math.sqrt(16))
print(round(mean(losses), 4))
print(dt.date(2026, 3, 1).isoformat())Output:
4.0
0.4825
2026-03-01
Each of the three lines shows one way to import:
import mathbrings in the whole module. You writemath.sqrt(...), so the name tells the reader wheresqrtcame from.from statistics import meanbrings in one name. You writemean(...)directly.import datetime as dtgives the module a short alias. A few aliases are conventions that everyone shares, for exampleimport numpy as npandimport pandas as pd, so use those exactly.
from math import *. It dumps every name into your file, and if two modules define the same name, the later import silently wins.ModuleNotFoundError: No module named 'requests'means the package is not installed in the environment Python is using.ImportError: cannot import name 'X' from 'pkg'means the package is there but has no such name, usually a typo or a version difference. The error decoder walks through the fix flow.
#Writing Your Own Module
.py file you write can be imported by another file in the same folder. The browser has no folder of your own files, so the cell below writes a file called metrics.py into a temporary folder first, then imports it. On your own machine you would just create the file in your editor.Try the import before the file exists, and watch it fail:
import importlib
import sys
import tempfile
from pathlib import Path
workdir = Path(tempfile.mkdtemp())
sys.path.insert(0, str(workdir))
try:
import metrics
except ModuleNotFoundError as err:
print("first try:", err)
(workdir / "metrics.py").write_text(
'''"""Small evaluation helpers."""
def accuracy(y_true, y_pred):
correct = sum(t == p for t, p in zip(y_true, y_pred))
return correct / len(y_true)
'''
)
importlib.invalidate_caches()
import metrics
print("second try:", metrics.accuracy([1, 0, 1, 1], [1, 0, 0, 1]))
print("module name:", metrics.__name__)
print("file name:", Path(metrics.__file__).name)Output:
first try: No module named 'metrics'
second try: 0.75
module name: metrics
file name: metrics.py
metrics and found no such file. The second works because the file now exists in a folder Python searches. Two lines in the cell are only there because the browser has no real folder: sys.path.insert tells Python to search the temporary folder, and importlib.invalidate_caches() makes it notice the new file. In a real project you need neither, because your script's own folder is searched automatically.metrics.__name__. Every module has a __name__, and for an imported module it is the module's name. The next section explains why that matters.#The name Guard
python metrics.py, it sets the file's __name__ to the string "__main__". When another file imports it, __name__ is the module's own name instead. A guard if __name__ == "__main__": lets one file be both a library others import and a script you run.run_name="__main__" means "pretend it was started from the terminal"):import importlib
import runpy
import sys
import tempfile
from pathlib import Path
workdir = Path(tempfile.mkdtemp())
sys.path.insert(0, str(workdir))
(workdir / "loud.py").write_text(
'''print("loud.py: __name__ is", __name__)
def accuracy(y_true, y_pred):
return sum(t == p for t, p in zip(y_true, y_pred)) / len(y_true)
print("loud.py: demo accuracy", accuracy([1, 0], [1, 1]))
'''
)
print("importing loud...")
importlib.invalidate_caches()
import loud
print("running loud as a script...")
runpy.run_path(str(workdir / "loud.py"), run_name="__main__")Output:
importing loud...
loud.py: __name__ is loud
loud.py: demo accuracy 0.5
running loud as a script...
loud.py: __name__ is __main__
loud.py: demo accuracy 0.5
accuracy now gets extra output, and if the demo loaded a dataset or called a network service, they would pay for that every time. Now the fix: move the demo under a guard, inside a function called main.import importlib
import runpy
import sys
import tempfile
from pathlib import Path
workdir = Path(tempfile.mkdtemp())
sys.path.insert(0, str(workdir))
(workdir / "quiet.py").write_text(
'''def accuracy(y_true, y_pred):
return sum(t == p for t, p in zip(y_true, y_pred)) / len(y_true)
def main():
print("quiet.py: demo accuracy", accuracy([1, 0], [1, 1]))
if __name__ == "__main__":
main()
'''
)
print("importing quiet...")
importlib.invalidate_caches()
import quiet
print("imported, nothing printed. __name__ inside is:", quiet.__name__)
print("running quiet as a script...")
runpy.run_path(str(workdir / "quiet.py"), run_name="__main__")Output:
importing quiet...
imported, nothing printed. __name__ inside is: quiet
running quiet as a script...
quiet.py: demo accuracy 0.5
uv init writes for you later in this lesson.helpers.py has print('loading', __name__) at the top level and a guarded block that prints 'demo'. main.py contains only 'import helpers'. You run 'python main.py'. What is printed?
#Packages: A Folder of Modules
__init__.py inside it. The file can be empty. Its presence tells Python the folder is importable. A small ML project might look like this:A small project with one package
train.py then imports with a dotted path, folder name first: from mlkit.metrics import accuracy. The cell below builds exactly this layout in a temporary folder. report.py imports from its neighbour using the full package path, which is the clearest style:import importlib
import sys
import tempfile
from pathlib import Path
root = Path(tempfile.mkdtemp())
sys.path.insert(0, str(root))
pkg = root / "mlkit"
pkg.mkdir()
(pkg / "__init__.py").write_text("")
(pkg / "metrics.py").write_text(
"def accuracy(y_true, y_pred):\n"
" return sum(t == p for t, p in zip(y_true, y_pred)) / len(y_true)\n"
)
(pkg / "report.py").write_text(
"from mlkit.metrics import accuracy\n"
"\n"
"def summary(y_true, y_pred):\n"
" return f'accuracy = {accuracy(y_true, y_pred):.2f}'\n"
)
importlib.invalidate_caches()
from mlkit.report import summary
import mlkit.metrics
print(summary([1, 0, 1, 1], [1, 0, 0, 1]))
print(mlkit.metrics.__name__)
print(sorted(name for name in sys.modules if name.startswith("mlkit")))
print(sys.path[0] == str(root))Output:
accuracy = 0.75
mlkit.metrics
['mlkit', 'mlkit.metrics', 'mlkit.report']
True
mlkit.report also loaded the package mlkit and the module mlkit.metrics it depends on. Python keeps every loaded module in sys.modules so a second import of the same name reuses it instead of running the file again.#How Python Finds a Module
import name, Python looks in this order. First, modules already loaded. Then the built-in and standard library modules. Then each folder in the list sys.path, which starts with the folder of the script you ran and ends with the site-packages folder of the environment in use. That last folder is where installed packages live, which is why the environment matters so much: the active environment decides which site-packages is on the path.numpy.py, shown as a real transcript:$ ls
numpy.py train.py
$ python train.py
Traceback (most recent call last):
File ".../train.py", line 3, in <module>
print(np.array([1, 2, 3]).sum())
^^^^^^^^
AttributeError: module 'numpy' has no attribute 'array'
numpy.py instead of the real library. The message says the module has no attribute, which sounds like a broken install, but the install is fine. Renaming the file (to stats_helpers.py, say) fixed it: the same train.py then printed 6. Never name your own files numpy.py, random.py, json.py, test.py or after any package you use.#Environments: One Folder per Project
.venv and kept inside your project. It holds a link to a Python interpreter and its own site-packages shelf, which starts empty. Installing a package puts it on that shelf only, and running Python from that environment makes Python look at that shelf.project-a/ project-b/
.venv/ .venv/
requests 2.31.0 requests 2.32.3
... ...
Two projects, two shelves, and each one gets the version it asked for. Create one with uv:
$ uv venv
Using CPython 3.12.13
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate
The first line names the Python version uv chose. Yours will differ, because it depends on what is installed on your machine and on your uv version. The other uv output in this lesson was captured the same way, on uv 0.10.9. The wording of uv's messages changes between releases, so expect yours to look similar, not identical.
$ source .venv/bin/activate
.venv\Scripts\activate, and in PowerShell it is .venv\Scripts\Activate.ps1. The Windows lines were not run on the machine used to check this lesson, so they come from the Python and uv documentation. After activating, python means the environment's Python, and the shell usually shows (.venv) at the start of the prompt. Type deactivate to leave.uv run, which appears below, finds the project's .venv itself. And a plain uv pip install in a folder that has a .venv installs there even if you forgot to activate. Activation matters most when you want to type python or pytest yourself.#Installing Packages with uv pip
Now install into the new environment. First check that nothing is there, then install:
$ python -c "import numpy"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'numpy'
$ uv pip install numpy
Resolved 1 package in 96ms
Downloading numpy (5.2MiB)
Downloaded numpy
Prepared 1 package in 373ms
Installed 1 package in 20ms
+ numpy==2.5.3
$ python -c "import numpy; print(numpy.__version__)"
2.5.3
+ line lists each package installed, with its exact version. The version number you get today will be newer than this one. uv pip install is deliberately close to pip install: it takes the same arguments, such as numpy==2.5.3 to pin a version, and it installs into the active environment.requests. Project A needs requests 2.31.0, so we install that:$ uv pip install requests==2.31.0
Resolved 5 packages in 93ms
Prepared 1 package in 20ms
Installed 5 packages in 9ms
+ certifi==2026.7.22
+ charset-normalizer==3.5.2
+ idna==3.20
+ requests==2.31.0
+ urllib3==2.8.0
requests brought four packages of its own, called dependencies. Then somebody works on project B in the same environment and installs the version it needs:$ uv pip install requests==2.32.3
Resolved 5 packages in 41ms
Prepared 1 package in 17ms
Uninstalled 1 package in 3ms
Installed 1 package in 1ms
- requests==2.31.0
+ requests==2.32.3
- line is the problem. The old version is gone, and project A, which was tested against 2.31.0, now quietly runs on 2.32.3. With one environment per project this cannot happen, because each project's installs land on its own shelf.Project A and project B share one environment. A needs requests 2.31.0 and was installed first. B then runs 'uv pip install requests==2.32.3'. What does project A import next time it runs?
uv pip list shows what is installed, and uv pip freeze prints each package as name==version, one per line:$ uv pip freeze
certifi==2026.7.22
charset-normalizer==3.5.2
idna==3.20
requests==2.32.3
urllib3==2.8.0
requirements.txt file you will meet shortly. First, a better way for a whole project.#Projects: pyproject.toml and uv.lock
uv pip install changes an environment but leaves no record of why. A project needs a written list of what it depends on. In uv, that list lives in a file called pyproject.toml, and uv init makes a project that already has one:$ uv init
Initialized project `proj`
$ ls -a
. .. .git .gitignore .python-version main.py pyproject.toml README.md
$ cat pyproject.toml
[project]
name = "proj"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = []
main.py already has the guard from earlier in this lesson, .gitignore already lists .venv, and uv also started a git repository (the .git folder). Now replace main.py with the numpy script from the start of the lesson and run it with uv run, which runs a command inside the project's environment, creating the environment if needed. It fails, as it should, because numpy is not a dependency yet:$ uv run main.py
Using CPython 3.12.13
Creating virtual environment at: .venv
Traceback (most recent call last):
File ".../main.py", line 1, in <module>
import numpy as np
ModuleNotFoundError: No module named 'numpy'
uv add, then run again:$ uv add numpy
Resolved 2 packages in 32ms
Downloading numpy (5.2MiB)
Downloaded numpy
Prepared 1 package in 573ms
Installed 1 package in 22ms
+ numpy==2.5.3
$ uv run main.py
mean per column: [2. 3.]
uv add did two things beyond installing. It wrote the dependency into pyproject.toml, and it created a second file:$ cat pyproject.toml
[project]
name = "proj"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=2.5.3",
]
$ head -6 uv.lock
version = 1
revision = 3
requires-python = ">=3.12"
[[package]]
name = "numpy"
version = "2.5.3"
pyproject.toml is what you wrote: numpy 2.5.3 or newer is acceptable. uv.lock is what uv decided: the exact version of every package, plus checksums for the downloads, 87 lines for this tiny project. Do not edit uv.lock by hand. Commit both files to git. Do not commit .venv, since it can always be rebuilt..venv, to an empty folder. This is what a teammate gets after git clone:$ ls -a
. .. .python-version main.py pyproject.toml uv.lock
$ uv sync
Using CPython 3.12.13
Creating virtual environment at: .venv
Resolved 8 packages in 2ms
Installed 6 packages in 38ms
+ iniconfig==2.3.0
+ numpy==2.5.3
+ packaging==26.3
+ pluggy==1.6.0
+ pygments==2.21.0
+ pytest==9.1.1
$ uv run main.py
mean per column: [2. 3.]
uv sync read uv.lock and installed exactly those versions. This project had also run uv add --dev pytest, which records a tool that only developers need in a separate dev group of pyproject.toml. That is why pytest appears: uv sync installs the dev group by default. Other useful project commands are uv remove numpy, which undoes an add, and uv tree, which shows what depends on what.uv init once, uv add when you need a package, uv run to run things, uv sync on a new machine.#Choosing the Python Version
pyproject.toml has requires-python = ">=3.12", and uv init also wrote a .python-version file containing 3.12. When uv needs a Python that is not on your machine, uv python install downloads one:$ uv python install 3.13
Downloading cpython-3.13.12-macos-aarch64-none (download) (16.9MiB)
Downloaded cpython-3.13.12-macos-aarch64-none (download)
Installed Python 3.13.12 in 3.02s
+ cpython-3.13.12-macos-aarch64-none (python3.13)
$ uv venv --python 3.13
Using CPython 3.13.12
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate
uv python list --only-installed shows every Python uv can find on your machine. The name shown in the transcript (macos-aarch64) describes this particular computer, so yours will name your own system. If a project says requires-python = ">=3.12" and your system Python is 3.9, you do not have to upgrade your system: let uv fetch a suitable Python for that one project.#pip and venv: The Version Everyone Else Shows
venv and pip come with Python itself. They do the same jobs with more typing, and almost every tutorial and CI file you will read uses them. You should be able to read them, and use them when uv is not available. Same steps, step by step:$ python -m venv .venv
$ source .venv/bin/activate
(.venv) $ pip install requests==2.32.3
Collecting requests==2.32.3
Downloading requests-2.32.3-py3-none-any.whl.metadata (4.6 kB)
...
Installing collected packages: urllib3, idna, charset-normalizer, certifi, requests
Successfully installed certifi-2026.7.22 charset-normalizer-3.5.2 idna-3.20 requests-2.32.3 urllib3-2.8.0
...; pip prints one Collecting and one Using cached line per dependency.) On Windows the activation line differs as shown earlier. The commands map one to one:| Job | venv and pip | uv |
|---|---|---|
| Make an environment | python -m venv .venv | uv venv |
| Install a package | pip install requests | uv pip install requests |
| List installed packages | pip list | uv pip list |
| Save exact versions | pip freeze > requirements.txt | uv pip freeze > requirements.txt |
| Install from that file | pip install -r requirements.txt | uv pip install -r requirements.txt |
uv venv does not contain pip, so python -m pip list inside it fails with No module named pip. Use uv pip there, or python -m venv if you want pip inside.name==version per line. It is the oldest way to share a setup, and it is what you will meet most in other people's projects. It has weaknesses compared with pyproject.toml and uv.lock: it mixes what you chose with what your choices pulled in, and it does not record a Python version. You can still write one from a uv project, for people who cannot use uv:$ uv export --no-hashes -o requirements.txt
$ cat requirements.txt
# This file was autogenerated by uv via the following command:
# uv export --no-hashes -o requirements.txt
colorama==0.4.6 ; sys_platform == 'win32'
# via pytest
iniconfig==2.3.0
# via pytest
numpy==2.5.3
# via proj
packaging==26.3
# via pytest
pluggy==1.6.0
# via pytest
pygments==2.21.0
# via pytest
pytest==9.1.1
# are comments. The line with ; sys_platform == 'win32' means "install this only on Windows". And this file installs with either tool. In a new folder, with uv:$ uv venv
$ uv pip install -r requirements.txt
Resolved 6 packages in 3ms
Installed 6 packages in 46ms
+ iniconfig==2.3.0
+ numpy==2.5.3
+ packaging==26.3
+ pluggy==1.6.0
+ pygments==2.21.0
+ pytest==9.1.1
pip freeze listed numpy 2.5.3 and pytest 9.1.1), which is the point: the file is portable.pip install outside any environment is refused on purpose:$ python3.13 -m pip install requests
error: externally-managed-environment
x This environment is externally managed
That message is the system telling you to use an environment. It is not a broken install.
#Reading Someone Else's Setup Instructions
A README tells you how to run a project, and it may use any tool. A short method works for most:
- Look at the files in the project's root folder. They tell you which tool the authors used.
- Pick the matching command from the table below.
- Make the environment first, install second, run last.
| You see | It means | Do this |
|---|---|---|
uv.lock and pyproject.toml | a uv project | uv sync, then uv run <command> |
requirements.txt only | the pip way | uv venv, then uv pip install -r requirements.txt |
pyproject.toml with a [project] table and a dependencies list, no lock file | standard packaging | uv sync, which also writes a uv.lock |
README says pip install -e . | install this project itself so imports work | uv venv, then uv pip install -e . |
.python-version or requires-python | the Python version it expects | uv python install if you lack it |
environment.yml, poetry.lock, Pipfile | conda, Poetry or Pipenv | read that tool's own instructions; this lesson does not cover them |
uv sync and uv pip install -e . rows were run on a hand-written pyproject.toml with a single numpy dependency and worked. A project whose pyproject.toml is configured for a different tool, such as Poetry, may not work with uv sync, so read its README before you guess.#Common Mistakes
.venv anywhere, uv refuses instead of guessing:$ uv pip install requests
error: No virtual environment found; run `uv venv` to create an environment, or pass `--system` to install into a non-virtual environment
uv venv. Avoid --system unless you have a reason.uv pip install numpy, the code works, and you send the folder to a friend with no pyproject.toml and no requirements.txt. The install is in your .venv and nowhere else. Use uv add numpy so the dependency is written down..venv to git, or copying it to a friend. An environment holds paths and compiled files tied to your computer. Keep .venv in .gitignore and share pyproject.toml and uv.lock instead.numpy.py transcript earlier showed. When an AttributeError says a real package has no attribute it definitely has, look for a file of your own with the same name.if __name__ == "__main__":, which makes every import run it.#Try It
min_max already. Do three things: add a standardize(values) function that subtracts the mean from each value and divides by the population standard deviation (statistics.pstdev), move the demo print under the __name__ guard, and print scaling.standardize([2, 4, 4, 4, 5, 5, 7, 9]). The expected result is [-1.5, -0.5, -0.5, -0.5, 0.0, 0.0, 1.0, 2.0], and importing the module should print nothing of its own.Tests: Importing scaling should print nothing by itself. The last line should print the list [-1.5, -0.5, -0.5, -0.5, 0.0, 0.0, 1.0, 2.0].
uv init, then uv add numpy. Open pyproject.toml and find numpy in dependencies. Delete the .venv folder, run uv sync, and check that uv run main.py still works. Then copy only pyproject.toml, uv.lock and main.py into a new folder and sync there. If both work, you have a project that rebuilds itself.#Key Takeaways
- A module is a
.pyfile and a package is a folder of them with an__init__.py. Python finds them throughsys.path, which starts with the folder of your script, so a file named like a library hides the library. if __name__ == "__main__":keeps a script's demo or entry point from running when the file is imported.- An environment is a folder with its own Python and its own shelf of packages. One per project stops projects from replacing each other's versions.
- uv is a Python package and project manager.
uv venvanduv pip installgive you the pip workflow, anduv init,uv add,uv runanduv syncgive you the project workflow. pyproject.tomlrecords what you asked for,uv.lockrecords the exact versions uv chose, and you commit both but never.venv.venv,pipandrequirements.txtstill work and are what most READMEs show. Each has a one-line uv equivalent, so translate instead of getting stuck.
A file named helpers.py has print('loading', __name__) at the top level, followed by a guarded block (if __name__ == '__main__') that prints 'demo'. This time you run the file itself with python helpers.py. What is printed?