Skip to content

Tooling

Every Python project needs the same few tools: an environment, a dependency manager, a linter and formatter, a type checker and a test runner. This page covers uv, venv and pip, pyproject.toml, ruff, mypy and pre-commit, and how a package is laid out. Most commands change your environment or need the network, so they are shown, not run.

I want to… Use… Example
start a new project uv init uv init --package shop (src layout)
install a Python version uv python install uv python install 3.13
pin the project’s Python uv python pin writes .python-version
create an environment uv venv / python -m venv .venv uv venv --python 3.13
activate it source .venv/bin/activate Windows: .venv\Scripts\activate
add a dependency uv add uv add "pandas>=3.1"
add a developer tool uv add --dev uv add --dev pytest ruff mypy
remove a dependency uv remove uv remove requests
lock exact versions uv lock writes uv.lock
upgrade one locked package uv lock --upgrade-package uv lock --upgrade-package pandas
make .venv match the lock uv sync uv sync --locked in CI
run a command in the project uv run uv run pytest -q
run a tool without installing it uvx uvx ruff check .
install a CLI tool globally uv tool install uv tool install pre-commit
a one-file script with its own dependencies uv add --script uv run report.py reads the inline metadata
pip-style install uv pip install / python -m pip install uv pip install -r requirements.txt
install my project for development an editable install uv pip install -e .
pin everything to a requirements file uv pip compile / uv export uv export -o requirements.txt
see what is installed uv pip list, uv tree uv tree --depth 1
lint ruff check ruff check --fix .
format ruff format ruff format --check . in CI
sort imports ruff check --select I --fix
explain a lint rule ruff rule CODE ruff rule B006
type check mypy mypy --strict src/
run checks before every commit pre-commit pre-commit install
build a wheel uv build writes dist/*.whl and dist/*.tar.gz
bump the version uv version --bump uv version --bump minor
run a module as a script python -m python -m shop data/sales.csv
add a command-line command [project.scripts] shop = "shop.cli:main"
read a package’s version in code importlib.metadata.version version("pandas")
check that a venv is active sys.prefix != sys.base_prefix True inside .venv

uv is a fast, all-in-one project manager: it installs Python, creates .venv, resolves and locks dependencies and runs tools.

Command Does
uv init [--package] [name] new project: pyproject.toml, .python-version, README.md; --package uses the src layout
uv add pkg, uv add --dev pkg, uv add --group docs pkg add to dependencies / the dev group / another group; then lock and sync
uv add --optional plots matplotlib add an extra: pip install "shop[plots]"
uv remove pkg remove a dependency
uv lock resolve all platforms; write uv.lock
uv lock --upgrade / --upgrade-package pkg allow newer versions in the lock
uv sync install exactly what uv.lock says, remove the rest
uv sync --locked fail if uv.lock is out of date (CI)
uv sync --frozen, --no-dev, --all-groups use the lock as is / skip dev tools / every group
uv run cmd sync, then run cmd inside .venv (no activation needed)
uv run --with rich script.py run with an extra package, just this once
uv tree the dependency tree
uv export --format requirements-txt -o requirements.txt the lock as a pinned requirements file
uv build / uv publish build a wheel and an sdist / upload to PyPI
uv python install 3.13, uv python list, uv python pin 3.13 manage interpreters
uv tool install ruff, uvx ruff global CLI tools / a temporary run
uv venv [--python 3.13] create .venv
uv pip install, uv pip sync, uv pip compile, uv pip freeze the pip-compatible interface
uv cache clean free disk space
report.py (a script with inline metadata)
# /// script
# requires-python = ">=3.12"
# dependencies = ["httpx>=0.28"]
# ///
import httpx # `uv run report.py` installs httpx in a cached environment
print(httpx.__version__)
Terminal
python -m venv .venv # create (standard library)
source .venv/bin/activate # macOS / Linux
.venv\Scripts\activate # Windows (PowerShell or cmd)
python -m pip install --upgrade pip # pip of this exact interpreter
python -m pip install "pandas>=3.1,<4" # install with a range
python -m pip install -r requirements.txt # install a list
python -m pip install -e ".[dev]" # editable install plus the dev extra
python -m pip freeze > requirements.txt # dump exact versions
python -m pip list --outdated # what could be upgraded
python -m pip show pandas # version, location, dependencies
python -m pip uninstall pandas
deactivate # leave the environment
Path macOS / Linux Windows
interpreter .venv/bin/python .venv\Scripts\python.exe
installed packages .venv/lib/python3.13/site-packages/ .venv\Lib\site-packages\
tools installed in the venv .venv/bin/ruff, .venv/bin/pytest .venv\Scripts\ruff.exe
import sys
from importlib.metadata import entry_points, version
print(sys.prefix != sys.base_prefix) # True inside a virtual environment
print(version("pytest"), version("ruff")) # distribution names, not import names
(script,) = entry_points(group="console_scripts", name="pytest")
print(script.value) # the function the `pytest` command calls
Output
True
9.2.0 0.17.4
_pytest.config:_console_main
File Holds Written by Commit?
pyproject.toml direct dependencies as ranges, metadata, tool settings you, uv add yes
uv.lock every package, exact versions and hashes, all platforms uv lock yes
requirements.in direct dependencies (pip-tools style input) you yes
requirements.txt name==version pins (or a loose list) you, pip freeze, uv pip compile, uv export yes, for applications
pylock.toml a lock in the standard PEP 751 format uv export --format pylock.toml yes
.python-version the project’s Python version uv python pin yes
.venv/ installed packages uv, venv no: add it to .gitignore
Project kind dependencies in pyproject.toml Reproducible installs
library (others install it) ranges: pandas>=3.1,<4 a lock for your own CI only
application, service, analysis ranges commit uv.lock (or a fully pinned requirements.txt)
from packaging.specifiers import SpecifierSet
versions = ["3.0.2", "3.1.0", "3.1.1", "3.2.0", "4.0.0"]
for spec in [">=3.1,<4", "~=3.1", "~=3.1.0", "==3.1.*", "!=3.1.0,>=3.1"]:
print(f"{spec:<14}", [v for v in versions if v in SpecifierSet(spec)])
Output
>=3.1,<4 ['3.1.0', '3.1.1', '3.2.0']
~=3.1 ['3.1.0', '3.1.1', '3.2.0']
~=3.1.0 ['3.1.0', '3.1.1']
==3.1.* ['3.1.0', '3.1.1']
!=3.1.0,>=3.1 ['3.1.1', '3.2.0', '4.0.0']
Specifier Allows
==3.1.1 exactly 3.1.1 (a pin)
>=3.1,<4 3.1 up to, not including, 4.0
~=3.1 >=3.1, ==3.* (compatible release)
~=3.1.0 >=3.1.0, ==3.1.*
==3.1.* any 3.1.x
pkg[extra] the package plus an extra’s dependencies
; sys_platform == "win32" an environment marker: only on Windows
; python_version < "3.13" only on older Pythons
pyproject.toml
[project]
name = "shop" # the distribution name on PyPI
version = "0.3.0"
description = "Clean and summarize shop sales data."
readme = "README.md"
requires-python = ">=3.12"
license = "MIT" # an SPDX expression
authors = [{ name = "Ada Lovelace", email = "ada@example.com" }]
dependencies = [ # what users need, as ranges
"pandas>=3.1,<4",
"httpx>=0.28",
]
[project.optional-dependencies] # extras: pip install "shop[plots]"
plots = ["matplotlib>=3.11"]
[project.scripts] # console commands
shop = "shop.cli:main" # `shop` calls shop/cli.py: main()
[project.entry-points."shop.plugins"] # plugin hooks other packages can read
csv = "shop.readers:read_csv"
[project.urls]
Homepage = "https://example.com/shop"
[dependency-groups] # developer tools, never shipped (PEP 735)
dev = ["pytest>=9.2", "pytest-cov>=7.1", "ruff>=0.17", "mypy>=2.4"]
[build-system] # how to build the wheel
requires = ["hatchling>=1.27"]
build-backend = "hatchling.build"
[tool.ruff] # every tool reads its own [tool.NAME] table
line-length = 88
[tool.mypy]
strict = true
[tool.pytest]
testpaths = ["tests"]
Table Read by Holds
[project] installers, build tools, PyPI name, version, Python range, dependencies (PEP 621)
[project.optional-dependencies] installers extras
[project.scripts] installers commands created in .venv/bin
[project.entry-points.*] importlib.metadata.entry_points plugin registrations
[dependency-groups] uv, pip 25.1+ (--group dev) dev, test and docs tools
[build-system] uv build, pip the build backend: hatchling, setuptools, uv_build, flit
[tool.*] each tool settings for ruff, mypy, pytest, coverage, uv
import tomllib
text = """
[project]
name = "shop"
dependencies = ["pandas>=3.1,<4"]
[project.scripts]
shop = "shop.cli:main"
[tool.ruff]
line-length = 88
"""
config = tomllib.loads(text) # tomllib.load(f) needs a file opened with "rb"
module, func = config["project"]["scripts"]["shop"].split(":")
print(module, func, config["tool"]["ruff"]["line-length"])
Output
shop.cli main 88
Terminal
ruff check . # lint the project
ruff check --fix . # apply safe fixes
ruff check --fix --unsafe-fixes . # also unsafe fixes: review the diff
ruff check --diff app.py # show fixes, change nothing
ruff check --select I --fix . # sort imports only
ruff check --statistics . # findings per rule
ruff check --watch . # re-lint on every save
ruff check --add-noqa . # silence every current finding (adopting ruff)
ruff format . # format like Black
ruff format --check . # exit 1 if a file would change (CI)
ruff format --diff app.py # show formatting changes
ruff rule B006 # explain one rule
Prefix Family Catches
E, W pycodestyle E501 long line, E711 == None, E722 bare except, W291 trailing spaces
F Pyflakes F401 unused import, F821 undefined name, F841 unused variable
I isort I001 unsorted imports
B flake8-bugbear B006 mutable default, B008 call in a default, B023 loop variable in a closure, B905 zip without strict
UP pyupgrade UP006 List → list, UP045 Optional → X | None, UP032 f-strings
SIM flake8-simplify SIM115 open without with, SIM108 ternary
C4 flake8-comprehensions C416 needless comprehension
PTH flake8-use-pathlib PTH118 os.path.join, PTH123 open()
RUF ruff’s own RUF005 unpacking instead of +, RUF100 unused noqa
N pep8-naming N802 function name not snake_case
S flake8-bandit (security) S602 shell=True, S608 SQL built with strings
PD, NPY pandas-vet, NumPy NPY002 legacy np.random calls
pyproject.toml
[tool.ruff]
line-length = 88
target-version = "py312"
extend-exclude = ["notebooks/scratch"]
[tool.ruff.lint]
select = ["E", "W", "F", "I", "B", "UP", "SIM", "C4", "PTH", "RUF", "S"]
ignore = ["E501"] # let the formatter handle line length
[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101"] # S101 flags assert; fine in tests
[tool.ruff.lint.isort]
known-first-party = ["shop"]
[tool.ruff.format]
quote-style = "double"
docstring-code-format = true

Silence one finding with # noqa: B006 at the end of the line. ruff’s default rule set is only E4, E7, E9 and F: select more on purpose.

Command Does
mypy src/ check the package
mypy --strict src/ require hints everywhere, no implicit Any
mypy --check-untyped-defs legacy.py check bodies of functions without hints
uv run mypy with files = ["src", "tests"] in [tool.mypy]

The full syntax and configuration are on the type hints page.

pre-commit runs checks on the staged files before each git commit and blocks the commit when one fails.

.pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files # blocks big data files by accident
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.4 # match the ruff version in your lock
hooks:
- id: ruff-check
args: [--fix]
- id: ruff-format
- repo: local
hooks:
- id: mypy
name: mypy
entry: uv run mypy
language: system
types: [python]
pass_filenames: false
Terminal
uv tool install pre-commit # or: uv add --dev pre-commit
pre-commit install # adds the git hook to this repository
pre-commit run --all-files # run every hook on every file now
pre-commit autoupdate # bump the rev: of each repo
git commit --no-verify # skip the hooks once (avoid)

A minimal CI job runs the same checks: uv sync --locked, uv run ruff check ., uv run ruff format --check ., uv run mypy, uv run pytest.

src layout
shop/ # the repository
├── pyproject.toml
├── uv.lock
├── README.md
├── .python-version
├── src/
│ └── shop/ # the import package: `import shop`
│ ├── __init__.py # runs on import; __version__, public names
│ ├── __main__.py # `python -m shop`
│ ├── cli.py # argparse; main() for [project.scripts]
│ ├── cleaning.py
│ └── py.typed # empty marker: "this package ships type hints"
└── tests/
├── conftest.py
└── test_cleaning.py
Choice Why
code under src/ tests import the installed package, not files that happen to sit in the working folder
uv sync or pip install -e . an editable install: code changes apply without a reinstall
__init__.py marks a regular package; keep it light (imports run on every import shop)
__main__.py with raise SystemExit(main()) python -m shop works and returns an exit code
py.typed mypy and pyright then use your hints for users of the package
if __name__ == "__main__": in scripts importing the file does not run the program
Command Runs
python -m shop args shop/__main__.py
python -m shop.cli shop/cli.py as __main__
python -m venv .venv create an environment
python -m pip install x pip for exactly this interpreter
python -m pytest -q pytest; also puts the current folder on sys.path
python -m json.tool data/config.json pretty-print JSON
python -m http.server 8000 serve the current folder
python -m sqlite3 data/shop.db an SQLite shell (3.12+)
python -m timeit "sum(range(1000))" a micro-benchmark
python -m cProfile -s cumulative app.py a profile
python -m pdb app.py the debugger
python -m zipfile -l archive.zip list an archive
python -m uuid print a new UUID (3.12+)
Kind pyproject.toml Result
console command [project.scripts] shop = "shop.cli:main" a shop executable in .venv/bin
GUI command [project.gui-scripts] no console window on Windows
plugin [project.entry-points."shop.plugins"] csv = "shop.readers:read_csv" discoverable with entry_points(group="shop.plugins")
src/shop/cli.py
import argparse
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="shop")
parser.add_argument("path")
args = parser.parse_args(argv) # None: read sys.argv
print(f"reading {args.path}")
return 0 # the exit code
if __name__ == "__main__":
raise SystemExit(main())

After uv sync (or pip install -e .), shop data/sales.csv, uv run shop data/sales.csv and python -m shop.cli data/sales.csv all call the same main().

Trap Symptom Fix
bare pip install installs into another Python than the one you run python -m pip or uv pip / uv add
no environment active packages land in the system Python, or pip refuses (externally-managed-environment) a .venv, or uv run
ModuleNotFoundError after an install the editor or terminal uses another interpreter select .venv/bin/python; check sys.executable
a moved or renamed .venv broken paths, commands fail delete it and run uv sync
.venv committed to git a huge repository, machine-specific files add .venv/ to .gitignore
>= ranges without a lock a fresh install pulls new versions and breaks commit uv.lock
== pins in a library’s dependencies users get resolver conflicts ranges in libraries; pins in lock files
pyproject.toml edited by hand uv.lock is stale; uv sync --locked fails uv lock after manual edits
version("sklearn") PackageNotFoundError use the distribution name: version("scikit-learn")
flat layout imports tests pass locally against files, fail when installed the src layout and an editable install
python pkg/cli.py with relative imports ImportError: attempted relative import with no known parent package python -m pkg.cli
a file named like a package (pandas.py) the real package is shadowed rename the file
ruff format and ruff check disagree on line length endless churn one line-length in [tool.ruff]; ignore E501 when formatting
# noqa without a code hides every rule on that line # noqa: F401
pre-commit hooks not installed hooks never run pre-commit install once per clone
ruff version in pre-commit differs from the lock CI and local results differ keep rev: equal to the locked version