aspect_rules_pyAPI docs @2.0.0-alpha.1

@aspect_rules_py//py:defs.bzl

Re-implementations of py_binary
and py_test

Choosing the Python version

The python_version attribute must refer to a python toolchain version
which has been registered in the MODULE.bazel file, e.g.:

python = use_extension("@rules_python//python/extensions:python.bzl", "python") python.toolchain(python_version = "3.8.12", is_default = False) python.toolchain(python_version = "3.9", is_default = True)

Functions & Macros

py_pytest_main

py_pytest_main wraps the template rendering target and the final py_library.

Parameters
*name

The name of the runable target that updates the test entry file.

py_library

Use this attribute to override the default py_library rule.

Default: <rule py_library>
deps

A list containing the pytest library target, e.g., @pypi_pytest//:pkg.

Default: []
data

A list of data dependencies to pass to the py_library target.

Default: []
testonly

A boolean indicating if the py_library target is testonly.

Default: True
kwargs

The extra arguments passed to the template rendering target.

py_venv
Parameters
kwargs
py_image_layer

Create OCI-compatible tars from a py_binary or py_venv target.

Pip-package grouping + compression is resolved from the //py:layer_tier
label_flag. Override globally with --//py:layer_tier=//path:custom_tier,
or pin a tier to a specific rule via the py_layer_tier attr below.

Output layers

  1. Non-pip deps listed in groups → one rule-created tar per group.
  2. First-party py_library targets matched by py_layer_tier.groups → one
    rule-created tar per group (aggregated across all matched targets in the
    binary's dep closure).
  3. Solo-group and subpath-split pip tars — built by _layer_aspect at each pip
    target's own namespace; globally shared across every rule using that package.
  4. Multi-member merged tars — one per group, built by _merge_aspect at the
    binary's namespace from the closure-filtered union of member install_dirs.
  5. Ungrouped pip packages → one squashed rule-created tar.
  6. Remaining first-party Python source files → the "default" layer.
Parameters
*name

Name of the generated target.

*binary

A py_venv or py_binary target.

groups

Maps a NON-PIP dep label to a group name. Each gets its own rule-created
tar. All pip-package grouping (whole-package, subpath, multi-member) belongs
in py_layer_tier — subpath glob keys passed here fail loudly.

Default: {}
group_execution_requirements

Maps a group name to execution requirement strings.
The group name "packages" applies to the squashed ungrouped-pip tar.

Default: {}
group_compress_levels

Maps a group name to a gzip compression level (1-9) for
rule-created tars (non-pip deps, squashed ungrouped pip tar, source). Default 6.
Does NOT apply to aspect-created pip tars (configure via the py_layer_tier target).

Default: {}
warn_remote_cache_threshold_mb

Threshold for large package warnings.

Default: 200
warn_layer_count

Warn when total layers exceed this. Default: 90.

Default: 90
platform

Platform transition target.

Default: None
layer_tier

Optional py_layer_tier target pinned for this rule. Sets the
@aspect_rules_py//py:layer_tier label_flag via the rule transition,
overriding any command-line value for this rule's subgraph.

Default: None
kwargs

Forwarded to inner rule.

resolutions.empty
resolutions.from_requirements
Parameters
*base
requirement_fn
Default: <function lambda from //py/private:virtual.bzl>
py_binary

Build and run a Python binary.

Splits the call into a sibling py_venv (which carries srcs / deps
/ imports / virtual_deps / resolutions / package_collisions /
include_*_site_packages / interpreter_options) plus a thin launcher
rule that exec's that venv's interpreter. Set expose_venv = True
to make the sibling a first-class :{name}.venv target — runnable
(bazel run :{name}.venv drops into the hermetic interpreter) and
pairable with py_venv_link for IDE integration.

Parameters
*name

Name of the rule.

srcs

Python source files.

Default: []
main

Entry point.
Like rules_python, this is treated as a suffix of a file that should appear among the srcs.
If absent, then [name].py is tried. As a final fallback, if the srcs has a single file,
that is used as the main.

Note: the fallback runs at macro-evaluation time and operates
on label strings, not resolved files — it cannot inspect a
generated target's output basename. If main would resolve
to a file produced by another rule (e.g. a genrule whose
output happens to be <name>.py), the macro can't see that
and you must pass main = explicitly.

Default: None
kwargs

additional named parameters forwarded to the
underlying rule and the sibling py_venv. One extra is
handled by this macro:

  • expose_venv (bool, default False) — when True, emit
    a sibling :{name}.venv py_venv carrying all venv-shaping
    attrs (deps, imports, package_collisions,
    include_*_site_packages, interpreter_options). The .venv
    target is runnable (bazel run :{name}.venv drops into
    the hermetic interpreter). To also materialise the venv as
    a workspace-local symlink for IDE integration, declare an
    explicit py_venv_link(name = "...", venv = ":{name}.venv")
    target.
py_test

Identical to py_binary, but produces a target that can be used with bazel test.

Parameters
*name

Name of the rule.

srcs

Python source files.

Default: []
main

Entry point.
Like rules_python, this is treated as a suffix of a file that should appear among the srcs.
If absent, then [name].py is tried. As a final fallback, if the srcs has a single file,
that is used as the main.

Default: None
pytest_main

If True, use a shared pytest entry point as the main.
The deps should include the pytest package (as well as the coverage package if desired).

Default: False
kwargs

additional named parameters forwarded to the
underlying rule and the sibling py_venv.

Rules

py_pex_binary

Build a pex executable from a py_binary

AttributeTypeDescription
*namename

A unique name for this target.

*binarylabel

A py_binary target

inject_envdictionary: String → String

Environment variables to set when running the pex binary.

Default: {}
inherit_pathstring

Whether to inherit the sys.path (aka PYTHONPATH) of the environment that the binary runs in.

Use false to not inherit sys.path; use fallback to inherit sys.path after packaged
dependencies; and use prefer to inherit sys.path before packaged dependencies.

Default: ""
python_shebangstring
Default: "#!/usr/bin/env python3"
python_interpreter_constraintslist of strings

Python interpreter versions this PEX binary is compatible with. A list of semver strings.
The placeholder strings {major}, {minor}, {patch} can be used for gathering version
information from the hermetic python toolchain.

Default: ["CPython=={major}.{minor}.*"]
py_library
AttributeTypeDescription
*namename

A unique name for this target.

virtual_depslist of strings
Default: []
srcslist of labels

Python source files.

Default: []
depslist of labels

Targets that produce Python code, commonly py_library rules.

Default: []
datalist of labels

Runtime dependencies of the program.

The transitive closure of the data dependencies will be available in the .runfiles
folder for this binary/test. The program may optionally use the Runfiles lookup library to
locate the data files, see https://pypi.org/project/bazel-runfiles/.

Default: []
importslist of strings

List of import directories to be added to the PYTHONPATH.

Default: []
resolutionsdictionary: Label → String

Satisfy a virtual_dep with a mapping from external package name to the label of an installed package that provides it.
See virtual_deps.

Default: {}
py_unpacked_wheel
AttributeTypeDescription
*namename

A unique name for this target.

*srclabel

The Wheel file, as defined by https://packaging.python.org/en/latest/specifications/binary-distribution-format/#binary-distribution-format

top_levelslist of strings

Names of the top-level packages / modules / *.dist-info directories the wheel installs into its site-packages.

When set, the target emits a PyWheelsInfo provider describing this wheel.
Downstream rules (such as py_binary) can consume this to assemble a merged
site-packages/ tree via ctx.actions.symlink instead of relying on .pth
entries. If left empty (the default), the target behaves as before — other
rules fall back to .pth-based import resolution.

Typically populated by the uv wheel-install repo rule. Hand-written
py_unpacked_wheel targets may populate this to opt into symlink-based
venv assembly.

Default: []
console_scriptslist of strings

Console-script entry points declared by this wheel, in the form "name=module:func".

py_binary consumes these via PyWheelsInfo to generate executable
wrappers under <venv>/bin/<name>. Typically populated from the wheel's
*.dist-info/entry_points.txt [console_scripts] section.

Default: []
namespace_top_levelslist of strings

Subset of top_levels that are PEP 420 namespace packages.

See the equivalent attribute on the whl_install rule for the full
story; short version: names listed here suppress collision errors when
multiple wheels claim the same top-level, because Python's namespace
machinery is meant to merge their contributions.

Default: []
py_layer_tier
AttributeTypeDescription
*namename

A unique name for this target.

groupsdictionary: String → String

Maps @pip//package → group name (whole pip package), @pip//package:glob → group name (pip subpath split), or //some/first_party:lib → group name (first-party PyInfo target). First-party main-repo labels may be written as //pkg:name; fully-qualified forms like @@//pkg:name are also accepted. A pip package may appear as a whole-package key OR with subpath globs, not both.

Default: {}
compressiondictionary: String → List of strings

Maps group name → [algorithm, level] for pip-derived layers. Applies to the whole-group tar, each subpath-split tar, and the multi-member merged tar — anything routed through py_layer_tier.groups. Example: {"heavy_pkgs": ["zstd", "1"]}. Untouched groups default to gzip -6.

Default: {}
interpreter_groupstring

When non-empty, the Python interpreter runfiles resolved from the binary's py toolchain are emitted as their own layer under this name instead of being bundled into the default source layer.

Default: ""
rootstring

Root path in the image. Default: '/app'.

Default: "/app"
strip_prefixstring

Prefix stripped from source file paths. Empty means use the binary's short_path.

Default: ""

Providers

PyLayerTierInfo

Layer tier for py_image_layer: how pip packages are grouped and compressed.

Fields
whole_groups

dict[str, str] — normalized pip label → group name.

subpath_groups

dict[str, dict[str, list[str]]] — label → {group_name: [glob_patterns]}.

compression

dict[str, list[str]] — group name → [algorithm, level].

multi_member_groups

dict[str, True] — group names with 2+ members in whole_groups.

interpreter_group

str — group name for the Python interpreter layer; '' disables.

root

str — root path in the image (e.g. '/app').

strip_prefix

str — prefix stripped from source file paths; empty means use binary short_path.

@aspect_rules_py//py:extensions.bzl

Module Extensions used from MODULE.bazel

Module Extensions

python_interpreters
Tag Classes
configure

Configure the set of python-build-standalone releases to search for interpreters.

AttributeTypeDescription
base_urlstring

Base URL for downloading release assets. Defaults to the official PBS GitHub releases URL.
Override this to fetch from a mirror or fork, e.g.
"https://github.com/my-org/python-build-standalone/releases/download".
The URL should point to the directory containing release date directories,
such that {base_url}/{date}/SHA256SUMS is a valid path.

Only honored from the root module.

Default: ""
*releaseslist of strings

List of python-build-standalone release dates to search for interpreters,
e.g. ["20260303", "20241002"]. Newer releases are preferred when multiple
contain the same Python minor version.

The special value "latest" resolves to the newest release via the GitHub
releases API. This makes the extension non-reproducible: Bazel will
re-evaluate it on every invocation rather than caching the result.

See https://github.com/astral-sh/python-build-standalone/releases for
available releases.

Only honored from the root module. Non-root modules may include this tag
without error, but it will be silently ignored.

local

Register a local (non-PBS) Python interpreter as a toolchain.

Exactly one of interpreter_path or env must be set. The interpreter is
probed for version info at repository-rule time. If the interpreter is
unavailable (path missing, env var unset), the toolchain is registered
but inactive — it will never match during toolchain resolution.

Local toolchains are registered before PBS toolchains, giving them higher
priority. Use config_settings to gate activation on a custom flag.

Only honored from the root module.

AttributeTypeDescription
config_settingslist of strings

Additional config_setting labels required for this toolchain to be selected.

Default: []
envstring

Environment variable pointing to a Python prefix directory (e.g. "VIRTUAL_ENV").
The interpreter is resolved as $ENV/bin/python3 (or $ENV/Scripts/python.exe on Windows).
If the variable is unset, the toolchain is registered but inactive (never matches).

Default: ""
exec_compatible_withlist of strings

Additional exec platform constraints for this toolchain.

Default: []
interpreter_pathstring

Absolute path to a Python interpreter binary.

Default: ""
python_versionstring

Override the detected Python version. If omitted, the interpreter is probed
at repository-rule evaluation time to determine its version.

Default: ""
target_compatible_withlist of strings

Additional target platform constraints for this toolchain.

Default: []
toolchain
AttributeTypeDescription
config_settingslist of strings

Additional config_setting labels that must match for this toolchain to be selected.
Use this to gate a toolchain on a custom flag, e.g.
["@//:use_hermetic_python"]. The settings are added to the toolchain's
target_settings alongside the version and platform constraints.

Only honored from the root module.

Default: []
exec_compatible_withlist of strings

Additional exec platform constraints appended to each platform variant's
exec_compatible_with list.

Only honored from the root module.

Default: []
is_defaultboolean

Only honored from the root module.

Default: False
pre_releaseboolean

Allow pre-release versions (alpha, beta, rc) for this toolchain.

By default, only final release versions are provisioned. Set this to True
to allow pre-release versions like 3.15.0a6 or 3.14.0b1. This is useful
for testing against upcoming Python versions that have no stable release yet.

Only honored from the root module.

Default: False
*python_versionstring

Python version to provision, e.g. '3.11' or '3.11.14'. The newest available patch version is used.

target_compatible_withlist of strings

Additional target platform constraints appended to each platform variant's
target_compatible_with list.

Only honored from the root module.

Default: []
py_tools
Tag Classes
rules_py_tools
AttributeTypeDescription
namename

Base name for generated repositories, allowing more than one toolchain to be registered.
Overriding the default is only permitted in the root module.

Default: "rules_py_tools"
is_prereleaseboolean

True iff there are no pre-built tool binaries for this version of rules_py

Default: True

@aspect_rules_py//py:toolchains.bzl

Declare toolchains

Functions & Macros

rules_py_toolchains

Create a downloaded toolchain for every tool under every supported platform.

Parameters
name

prefix used in created repositories

Default: "rules_py_tools"
is_prerelease

True iff there are no pre-built tool binaries for this version of rules_py

Default: True