@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_mainpy_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_venvParameters
kwargs |
py_venv_linkEmit a runnable target that materialises venv into the workspace.
bazel run :<name> creates a symlink in $BUILD_WORKING_DIRECTORY
(typically the workspace root) that points at venv's materialised
venv tree in bazel-bin, so IDEs / LSPs can resolve interpreter and
site-packages via a stable workspace-local path.
Parameters
*name | Runnable target name. |
*venv | Label of a |
link_name | Workspace-relative basename for the created Default: None |
kwargs | Forwarded to the underlying |
py_image_layerCreate 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
- Non-pip deps listed in
groups→ one rule-created tar per group. - 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). - Solo-group and subpath-split pip tars — built by
_layer_aspectat each pip
target's own namespace; globally shared across every rule using that package. - Multi-member merged tars — one per group, built by
_merge_aspectat the
binary's namespace from the closure-filtered union of member install_dirs. - Ungrouped pip packages → one squashed rule-created tar.
- 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 Default: {} |
group_execution_requirements | Maps a group name to execution requirement strings. Default: {} |
group_compress_levels | Maps a group name to a gzip compression level (1-9) for 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 Default: None |
kwargs | Forwarded to inner rule. |
resolutions.emptyresolutions.from_requirementsParameters
*base | |
requirement_fn | Default: <function lambda from //py/private:virtual.bzl> |
py_binaryBuild 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. Note: the fallback runs at macro-evaluation time and operates Default: None |
kwargs | additional named parameters forwarded to the
|
py_testIdentical 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. Default: None |
pytest_main | If True, use a shared pytest entry point as the main. Default: False |
kwargs | additional named parameters forwarded to the |
Rules
py_pex_binaryBuild a pex executable from a py_binary
| Attribute | Type | Description |
|---|---|---|
*name | name | A unique name for this target. |
*binary | label | A py_binary target |
inject_env | dictionary: String → String | Environment variables to set when running the pex binary. Default: {} |
inherit_path | string | Whether to inherit the Use Default: "" |
python_shebang | string | Default: "#!/usr/bin/env python3" |
python_interpreter_constraints | list of strings | Python interpreter versions this PEX binary is compatible with. A list of semver strings. Default: ["CPython=={major}.{minor}.*"] |
py_library| Attribute | Type | Description |
|---|---|---|
*name | name | A unique name for this target. |
virtual_deps | list of strings | Default: [] |
srcs | list of labels | Python source files. Default: [] |
deps | list of labels | Targets that produce Python code, commonly Default: [] |
data | list of labels | Runtime dependencies of the program. The transitive closure of the Default: [] |
imports | list of strings | List of import directories to be added to the PYTHONPATH. Default: [] |
resolutions | dictionary: Label → String | Satisfy a virtual_dep with a mapping from external package name to the label of an installed package that provides it. Default: {} |
py_unpacked_wheel| Attribute | Type | Description |
|---|---|---|
*name | name | A unique name for this target. |
*src | label | The Wheel file, as defined by https://packaging.python.org/en/latest/specifications/binary-distribution-format/#binary-distribution-format |
top_levels | list 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 Typically populated by the Default: [] |
console_scripts | list of strings | Console-script entry points declared by this wheel, in the form
Default: [] |
namespace_top_levels | list of strings | Subset of See the equivalent attribute on the Default: [] |
py_layer_tier| Attribute | Type | Description |
|---|---|---|
*name | name | A unique name for this target. |
groups | dictionary: 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: {} |
compression | dictionary: 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_group | string | 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: "" |
root | string | Root path in the image. Default: '/app'. Default: "/app" |
strip_prefix | string | Prefix stripped from source file paths. Empty means use the binary's short_path. Default: "" |
Providers
PyLayerTierInfoLayer 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_interpretersTag Classes
configureConfigure the set of python-build-standalone releases to search for interpreters.
| Attribute | Type | Description |
|---|---|---|
base_url | string | Base URL for downloading release assets. Defaults to the official PBS GitHub releases URL. Only honored from the root module. Default: "" |
*releases | list of strings | List of python-build-standalone release dates to search for interpreters, The special value "latest" resolves to the newest release via the GitHub See https://github.com/astral-sh/python-build-standalone/releases for Only honored from the root module. Non-root modules may include this tag |
localRegister 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.
| Attribute | Type | Description |
|---|---|---|
config_settings | list of strings | Additional config_setting labels required for this toolchain to be selected. Default: [] |
env | string | Environment variable pointing to a Python prefix directory (e.g. "VIRTUAL_ENV"). Default: "" |
exec_compatible_with | list of strings | Additional exec platform constraints for this toolchain. Default: [] |
interpreter_path | string | Absolute path to a Python interpreter binary. Default: "" |
python_version | string | Override the detected Python version. If omitted, the interpreter is probed Default: "" |
target_compatible_with | list of strings | Additional target platform constraints for this toolchain. Default: [] |
toolchain| Attribute | Type | Description |
|---|---|---|
config_settings | list of strings | Additional config_setting labels that must match for this toolchain to be selected. Only honored from the root module. Default: [] |
exec_compatible_with | list of strings | Additional exec platform constraints appended to each platform variant's Only honored from the root module. Default: [] |
is_default | boolean | Only honored from the root module. Default: False |
pre_release | boolean | Allow pre-release versions (alpha, beta, rc) for this toolchain. By default, only final release versions are provisioned. Set this to True Only honored from the root module. Default: False |
*python_version | string | Python version to provision, e.g. '3.11' or '3.11.14'. The newest available patch version is used. |
target_compatible_with | list of strings | Additional target platform constraints appended to each platform variant's Only honored from the root module. Default: [] |
py_toolsTag Classes
rules_py_tools| Attribute | Type | Description |
|---|---|---|
name | name | Base name for generated repositories, allowing more than one toolchain to be registered. Default: "rules_py_tools" |
is_prerelease | boolean | 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_toolchainsCreate 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 |