TExcelTAD

Pants Compared

Pants (v2, a rewrite from 2020 with a Rust engine and Python plugins) takes a different position from Bazel and Buck2: it aims to give monorepo builds to teams that don't want to write BUILD files by hand. Its signature feature is dependency inference: Pants reads your imports and works out the dependency graph itself. It started Python-first and now also supports Go, Java, Scala, Kotlin, shell, Docker, Helm, Terraform and (experimentally) JavaScript.

Note: Pants downloads its own Python distribution and plugins on first run, so it can't run in the offline course image. Files and commands below are shown, not run; the runnable model shows the idea behind dependency inference.

A Pants repository

toml
# pants.toml
[GLOBAL]
pants_version = "X.Y.Z"            # pin the Pants release you use
backend_packages = [
  "pants.backend.python",
  "pants.backend.python.lint.black",
  "pants.backend.python.typecheck.mypy",
  "pants.backend.docker",
]

[python]
interpreter_constraints = ["CPython==3.13.*"]
enable_resolves = true
default_resolve = "python-default"

[python.resolves]
python-default = "3rdparty/python/default.lock"
python
# src/shop/BUILD: one line per directory, written by `pants tailor`
python_sources()
python_tests(name = "tests")
python
# 3rdparty/python/BUILD
python_requirements(source = "requirements.txt")

There are no deps lists. python_sources() is a target generator: it creates one target per file, and each file's dependencies are inferred from its import statements (first-party modules by source root, third-party ones through the requirements' module mappings).

bash
pants tailor ::                       # create missing BUILD files
pants dependencies src/shop/cart.py   # show inferred deps of one file
pants dependents --transitive src/shop/money.py
pants test ::                         # `::` = everything, like Bazel's //...
pants lint fmt check ::               # linters, formatters, type checkers as goals
pants package src/shop:app            # PEX, wheel, Docker image…
pants --changed-since=origin/main --changed-dependents=transitive test
pants generate-lockfiles              # resolves → lockfiles

Dependency inference, modelled

python · try it yourself
import ast, textwrap

FILES = {
    "src/shop/money.py": "def cents(x): return round(x * 100)",
    "src/shop/cart.py": "from shop.money import cents\nimport requests\n\ndef total(items): return sum(cents(i) for i in items)",
    "src/shop/cart_test.py": "from shop.cart import total\nimport pytest\n\ndef test(): assert total([1.5]) == 150",
    "src/tools/report.py": "import shop.cart\nimport json",
}
SOURCE_ROOT = "src/"
THIRD_PARTY = {"requests": "3rdparty/python:reqs#requests", "pytest": "3rdparty/python:reqs#pytest"}

def module_of(path):
    return path[len(SOURCE_ROOT):-3].replace("/", ".")

OWNERS = {module_of(p): p for p in FILES}

def infer(path):
    deps = set()
    for node in ast.walk(ast.parse(FILES[path])):
        names = [a.name for a in node.names] if isinstance(node, ast.Import) else \
                [node.module] if isinstance(node, ast.ImportFrom) else []
        for name in names:
            if name in OWNERS:
                deps.add(OWNERS[name])
            elif name.split(".")[0] in THIRD_PARTY:
                deps.add(THIRD_PARTY[name.split(".")[0]])
            # anything else (json, os…) is the standard library: no dependency
    return sorted(deps)

for path in FILES:
    print(f"{path:24} -> {infer(path)}")

def dependents(target):
    out = {p for p in FILES if target in infer(p)}
    for p in list(out):
        out |= dependents(p)
    return out

print("changed money.py, run tests in:", sorted(p for p in dependents("src/shop/money.py") if p.endswith("_test.py")))
src/shop/money.py        -> []
src/shop/cart.py         -> ['3rdparty/python:reqs#requests', 'src/shop/money.py']
src/shop/cart_test.py    -> ['3rdparty/python:reqs#pytest', 'src/shop/cart.py']
src/tools/report.py      -> ['src/shop/cart.py']
changed money.py, run tests in: ['src/shop/cart_test.py']

That's the core of pants --changed-since=… --changed-dependents=transitive test: map files to modules, imports to owners, and walk the reverse graph. When inference is ambiguous (two files provide the same module) or impossible (dynamic imports, plugins loaded by name), you add explicit dependencies=[...] to the target, and Pants warns about ambiguity rather than guessing.

Compared with Bazel

Bazel Pants
BUILD files explicit targets and deps mostly boilerplate (python_sources()), generated by tailor; deps inferred
Granularity as fine as you declare per file automatically
Language focus C++, Java, Go, everything Python, JVM, Go, shell, Docker; no C++
Tool integration rules per tool (rules_mypy, rules_lint) lint, format, typecheck, test, package as built-in goals with many tools
Extending Starlark rules Python plugins against the Pants rule engine
Hermeticity sandbox, hermetic toolchains sandboxed processes in temp dirs, pinned interpreters and lockfiles
Caching / RE local, disk, remote (REAPI), RBE local, remote cache (REAPI), remote execution (REAPI)
Lockfiles MODULE.bazel.lock + language-specific ones per resolve: pants generate-lockfiles

Pants is a strong choice for a Python-heavy monorepo whose developers would otherwise maintain deps lists by hand; Bazel's Python story needs Gazelle's Python plugin to get close. For C++ or mixed native code, Pants is not an option.

Test yourself

What is Pants' 'dependency inference'?

  1. Guessing versions
  2. Deriving each file's dependencies from its import statements
  3. A remote cache
  4. Sorting tests

What does :: mean in a Pants command?

  1. The root directory only
  2. All targets recursively, like Bazel's //...
  3. The current file
  4. Third-party code

Which language is a poor fit for Pants?

  1. Python
  2. Go
  3. C++
  4. Shell