Python: py_binary, py_library, py_test
Python has no compile step, so why build it with Bazel? Because in a monorepo Python code depends on generated code (protobuf, config), on C++ extensions and on tools from other languages, and because bazel test can then run exactly the Python tests a change affects. The rules come from rules_python (2.4.5 here):
| Rule | Purpose |
|---|---|
py_library |
a group of .py files plus their deps and data |
py_binary |
an executable: a launcher script that runs main (default <name>.py) with the right interpreter and import path |
py_test |
a py_binary that bazel test runs; exit code 0 = pass (unittest and pytest both work) |
A library, a tool and a test
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_python", version = "2.4.5")' > MODULE.bazel
mkdir -p textstats
cat > textstats/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")
py_library(
name = "stats",
srcs = ["stats.py"],
)
py_binary(
name = "wc",
srcs = ["wc.py"],
deps = [":stats"],
)
py_test(
name = "stats_test",
size = "small",
srcs = ["stats_test.py"],
deps = [":stats"],
)
EOF
cat > textstats/stats.py <<'EOF'
def word_count(text):
return len(text.split())
def longest_word(text):
return max(text.split(), key=len, default="")
EOF
cat > textstats/wc.py <<'EOF'
import sys
from textstats.stats import longest_word, word_count
text = " ".join(sys.argv[1:])
print(f"{word_count(text)} words, longest: {longest_word(text)!r}")
print("running on Python", sys.version.split()[0])
EOF
cat > textstats/stats_test.py <<'EOF'
import unittest
from textstats.stats import longest_word, word_count
class StatsTest(unittest.TestCase):
def test_count(self):
self.assertEqual(word_count("a bb ccc"), 3)
def test_longest(self):
self.assertEqual(longest_word("a bb ccc"), "ccc")
if __name__ == "__main__":
unittest.main()
EOF
bazel run //textstats:wc -- hermetic builds are reproducible 2>/dev/null
python3 --version
bazel test //textstats:stats_test 2>&1 | grep -E 'PASSED|FAILED|Executed'4 words, longest: 'reproducible'
running on Python 3.14.4
Python 3.12.3
//textstats:stats_test PASSED in 0.3s
Executed 1 out of 1 test: 1 test passes.
Three things to notice:
Imports are workspace-relative:
from textstats.stats import …. The launcher puts the runfiles root onsys.path. (rules_pythoncan also add a directory withimports = ["."], but repository-wide absolute imports keep names unique, just like C++ headers.)The program ran on Python 3.14.4 from a downloaded interpreter, not the system's 3.12:
rules_pythonregisters a hermetic Python toolchain (python-build-standalone) by default, so every developer and CI machine uses the same interpreter. Choose the version inMODULE.bazel:pythonpython = use_extension("@rules_python//python/extensions:python.bzl", "python") python.toolchain(python_version = "3.14", is_default = True)Arguments after
--go to the program, not to Bazel.
Runfiles: data files at run time
A Python program that reads a file at run time must declare it in data. Bazel then places it in the binary's runfiles tree, a directory next to the launcher that mirrors the workspace, and the program looks it up with the runfiles library instead of a path relative to the current directory (which differs between bazel run, bazel test and a deployed binary):
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_python", version = "2.4.5")' > MODULE.bazel
mkdir -p greeter
cat > greeter/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_binary")
py_binary(
name = "greeter",
srcs = ["greeter.py"],
data = ["greetings.txt"],
deps = ["@rules_python//python/runfiles"],
)
EOF
printf 'hello\nbonjour\nxin chao\n' > greeter/greetings.txt
cat > greeter/greeter.py <<'EOF'
from python.runfiles import runfiles
r = runfiles.Create()
path = r.Rlocation("_main/greeter/greetings.txt")
for line in open(path):
print(line.strip().title() + "!")
EOF
bazel build //greeter 2>/dev/null
./bazel-bin/greeter/greeter
find bazel-bin/greeter/greeter.runfiles/_main -maxdepth 2 | sortHello!
Bonjour!
Xin Chao!
bazel-bin/greeter/greeter.runfiles/_main
bazel-bin/greeter/greeter.runfiles/_main/greeter
bazel-bin/greeter/greeter.runfiles/_main/greeter/_greeter.venv
bazel-bin/greeter/greeter.runfiles/_main/greeter/_greeter_stage2_bootstrap.py
bazel-bin/greeter/greeter.runfiles/_main/greeter/greeter
bazel-bin/greeter/greeter.runfiles/_main/greeter/greeter.build_data.txt
bazel-bin/greeter/greeter.runfiles/_main/greeter/greeter.py
bazel-bin/greeter/greeter.runfiles/_main/greeter/greetings.txt
Besides your files, the tree holds rules_python's launcher machinery (_greeter.venv, a stage-2 bootstrap script, build data). _main is the runfiles name of the main repository; files from an external module appear under its canonical name (for example rules_python+). Running ./bazel-bin/greeter/greeter directly works too: the launcher finds its runfiles tree next to itself.
Third-party packages (not run here)
PyPI packages come in through a module extension that reads a locked requirements file and creates one repository per package:
pip = use_extension("@rules_python//python/extensions:pip.bzl", "pip")
pip.parse(
hub_name = "pypi",
python_version = "3.14",
requirements_lock = "//:requirements_lock.txt", # pinned, with hashes
)
use_repo(pip, "pypi")py_binary(
name = "report",
srcs = ["report.py"],
deps = ["@pypi//requests", "@pypi//rich"],
)Generate requirements_lock.txt with pip-compile --generate-hashes or uv pip compile --generate-hashes (see Python Packaging for lockfiles), or with rules_python's compile_pip_requirements rule. The course image has no PyPI mirror, so this part is not run. The rule of thumb: Bazel doesn't resolve Python versions, it installs exactly what the lock says.
Python-specific advice
| Topic | Advice |
|---|---|
__init__.py |
the course image sets rules_python's future default --incompatible_default_to_explicit_init_py: Bazel no longer creates empty __init__.py files for you, so namespace packages behave like normal Python |
| Type checking | run mypy or pyright as a separate test or aspect (e.g. rules_mypy), not inside py_test |
pytest |
py_test(main = "run_pytest.py") with a tiny wrapper that calls pytest.main([...]), or a macro such as py_pytest_test from rules_python_pytest |
| Packaging | py_wheel builds a wheel from py_library targets; use it for libraries you publish |
Test yourself
Which interpreter did bazel run //textstats:wc use?
- The system python3
- A hermetic CPython downloaded and registered as a toolchain by rules_python
- Pyodide
- Whatever is first on PATH
How should a py_binary find a data file at run time?
- open('greetings.txt') relative to the current directory
- Declare it in
dataand look it up through the runfiles library - Hard-code an absolute path
- Copy it to /tmp in a genrule
How are PyPI dependencies brought into a Bzlmod build?
pip installin a genrule- The
pip.parsemodule extension reads a locked requirements file - bazel_dep on each package
- They can't be