Python Rules

Report an issue View source Nightly · 7.3 · 7.2 · 7.1 · 7.0 · 6.5

Rules

py_binary

View rule source
py_binary(name, deps, srcs, data, args, compatible_with, deprecation, distribs, env, exec_compatible_with, exec_properties, features, imports, legacy_create_init, licenses, main, output_licenses, precompile, precompile_invalidation_mode, precompile_optimize_level, precompile_source_retention, pyc_collection, python_version, restricted_to, srcs_version, stamp, tags, target_compatible_with, testonly, toolchains, visibility)

Arguments

Attributes
name

Name; required

A unique name for this target.

deps

List of labels; default is []

List of additional libraries to be linked in to the target. See comments about the [`deps` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). These are typically `py_library` rules. Targets that only provide data files used at runtime belong in the `data` attribute.
srcs

List of labels; required

The list of Python source files that are processed to create the target. This includes all your checked-in code and may include generated source files. The `.py` files belong in `srcs` and library targets belong in `deps`. Other binary files that may be needed at run time belong in `data`.
data

List of labels; default is []

The list of files need by this library at runtime. See comments about the [`data` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). There is no `py_embed_data` like there is `cc_embed_data` and `go_embed_data`. This is because Python has a concept of runtime resources.
imports

List of strings; default is []

List of import directories to be added to the PYTHONPATH. Subject to "Make variable" substitution. These import directories will be added for this rule and all rules that depend on it (note: not the rules this rule depends on. Each directory will be added to `PYTHONPATH` by `py_binary` rules that depend on this rule. The strings are repo-runfiles-root relative, Absolute paths (paths that start with `/`) and paths that references a path above the execution root are not allowed and will result in an error.
legacy_create_init

Integer; default is -1

Whether to implicitly create empty `__init__.py` files in the runfiles tree. These are created in every directory containing Python source code or shared libraries, and every parent directory of those directories, excluding the repo root directory. The default, `-1` (auto), means true unless `--incompatible_default_to_explicit_init_py` is used. If false, the user is responsible for creating (possibly empty) `__init__.py` files and adding them to the `srcs` of Python targets as required.
main

Label; default is None

Optional; the name of the source file that is the main entry point of the application. This file must also be listed in `srcs`. If left unspecified, `name`, with `.py` appended, is used instead. If `name` does not match any filename in `srcs`, `main` must be specified.
precompile

String; default is "inherit"

Whether py source files **for this target** should be precompiled. Values: * `inherit`: Determine the value from the {flag}`--precompile` flag. * `enabled`: Compile Python source files at build time. Note that --precompile_add_to_runfiles affects how the compiled files are included into a downstream binary. * `disabled`: Don't compile Python source files at build time. * `if_generated_source`: Compile Python source files, but only if they're a generated file. :::{seealso} * The {flag}`--precompile` flag, which can override this attribute in some cases and will affect all targets when building. * The {obj}`pyc_collection` attribute for transitively enabling precompiling on a per-target basis. * The [Precompiling](precompiling) docs for a guide about using precompiling. :::
precompile_invalidation_mode

String; default is "auto"

How precompiled files should be verified to be up-to-date with their associated source files. Possible values are: * `auto`: The effective value will be automatically determined by other build settings. * `checked_hash`: Use the pyc file if the hash of the source file matches the hash recorded in the pyc file. This is most useful when working with code that you may modify. * `unchecked_hash`: Always use the pyc file; don't check the pyc's hash against the source file. This is most useful when the code won't be modified. For more information on pyc invalidation modes, see https://docs.python.org/3/library/py_compile.html#py_compile.PycInvalidationMode
precompile_optimize_level

Integer; default is 0

The optimization level for precompiled files. For more information about optimization levels, see the `compile()` function's `optimize` arg docs at https://docs.python.org/3/library/functions.html#compile NOTE: The value `-1` means "current interpreter", which will be the interpreter used _at build time when pycs are generated_, not the interpreter used at runtime when the code actually runs.
precompile_source_retention

String; default is "inherit"

Determines, when a source file is compiled, if the source file is kept in the resulting output or not. Valid values are: * `inherit`: Inherit the value from the {flag}`--precompile_source_retention` flag. * `keep_source`: Include the original Python source. * `omit_source`: Don't include the original py source. * `omit_if_generated_source`: Keep the original source if it's a regular source file, but omit it if it's a generated file.
pyc_collection

String; default is "inherit"

Determines whether pyc files from dependencies should be manually included. NOTE: This setting is only useful with {flag}`--precompile_add_to_runfiles=decided_elsewhere`. Valid values are: * `inherit`: Inherit the value from {flag}`--pyc_collection`. * `include_pyc`: Add pyc files from dependencies in the binary (from {obj}`PyInfo.transitive_pyc_files`. * `disabled`: Don't explicitly add pyc files from dependencies. Note that pyc files may still come from dependencies if a target includes them as part of their runfiles (such as when {obj}`--precompile_add_to_runfiles=always` is used).
python_version

String; default is "PY3"

Defunct, unused, does nothing.
srcs_version

String; default is "PY2AND3"

Defunct, unused, does nothing.
stamp

Integer; default is -1

Whether to encode build information into the binary. Possible values: * `stamp = 1`: Always stamp the build information into the binary, even in `--nostamp` builds. **This setting should be avoided**, since it potentially kills remote caching for the binary and any downstream actions that depend on it. * `stamp = 0`: Always replace build information by constant values. This gives good build result caching. * `stamp = -1`: Embedding of build information is controlled by the `--[no]stamp` flag. Stamped binaries are not rebuilt unless their dependencies change. WARNING: Stamping can harm build performance by reducing cache hits and should be avoided if possible.

py_library

View rule source
py_library(name, deps, srcs, data, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, imports, licenses, precompile, precompile_invalidation_mode, precompile_optimize_level, precompile_source_retention, restricted_to, srcs_version, tags, target_compatible_with, testonly, toolchains, visibility)
A library of Python code that can be depended upon. Default outputs: * The input Python sources * The precompiled artifacts from the sources. NOTE: Precompilation affects which of the default outputs are included in the resulting runfiles. See the precompile-related attributes and flags for more information.

Arguments

Attributes
name

Name; required

A unique name for this target.

deps

List of labels; default is []

List of additional libraries to be linked in to the target. See comments about the [`deps` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). These are typically `py_library` rules. Targets that only provide data files used at runtime belong in the `data` attribute.
srcs

List of labels; default is []

The list of Python source files that are processed to create the target. This includes all your checked-in code and may include generated source files. The `.py` files belong in `srcs` and library targets belong in `deps`. Other binary files that may be needed at run time belong in `data`.
data

List of labels; default is []

The list of files need by this library at runtime. See comments about the [`data` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). There is no `py_embed_data` like there is `cc_embed_data` and `go_embed_data`. This is because Python has a concept of runtime resources.
imports

List of strings; default is []

List of import directories to be added to the PYTHONPATH. Subject to "Make variable" substitution. These import directories will be added for this rule and all rules that depend on it (note: not the rules this rule depends on. Each directory will be added to `PYTHONPATH` by `py_binary` rules that depend on this rule. The strings are repo-runfiles-root relative, Absolute paths (paths that start with `/`) and paths that references a path above the execution root are not allowed and will result in an error.
precompile

String; default is "inherit"

Whether py source files **for this target** should be precompiled. Values: * `inherit`: Determine the value from the {flag}`--precompile` flag. * `enabled`: Compile Python source files at build time. Note that --precompile_add_to_runfiles affects how the compiled files are included into a downstream binary. * `disabled`: Don't compile Python source files at build time. * `if_generated_source`: Compile Python source files, but only if they're a generated file. :::{seealso} * The {flag}`--precompile` flag, which can override this attribute in some cases and will affect all targets when building. * The {obj}`pyc_collection` attribute for transitively enabling precompiling on a per-target basis. * The [Precompiling](precompiling) docs for a guide about using precompiling. :::
precompile_invalidation_mode

String; default is "auto"

How precompiled files should be verified to be up-to-date with their associated source files. Possible values are: * `auto`: The effective value will be automatically determined by other build settings. * `checked_hash`: Use the pyc file if the hash of the source file matches the hash recorded in the pyc file. This is most useful when working with code that you may modify. * `unchecked_hash`: Always use the pyc file; don't check the pyc's hash against the source file. This is most useful when the code won't be modified. For more information on pyc invalidation modes, see https://docs.python.org/3/library/py_compile.html#py_compile.PycInvalidationMode
precompile_optimize_level

Integer; default is 0

The optimization level for precompiled files. For more information about optimization levels, see the `compile()` function's `optimize` arg docs at https://docs.python.org/3/library/functions.html#compile NOTE: The value `-1` means "current interpreter", which will be the interpreter used _at build time when pycs are generated_, not the interpreter used at runtime when the code actually runs.
precompile_source_retention

String; default is "inherit"

Determines, when a source file is compiled, if the source file is kept in the resulting output or not. Valid values are: * `inherit`: Inherit the value from the {flag}`--precompile_source_retention` flag. * `keep_source`: Include the original Python source. * `omit_source`: Don't include the original py source. * `omit_if_generated_source`: Keep the original source if it's a regular source file, but omit it if it's a generated file.
srcs_version

String; default is "PY2AND3"

Defunct, unused, does nothing.

py_test

View rule source
py_test(name, deps, srcs, data, args, compatible_with, deprecation, distribs, env, env_inherit, exec_compatible_with, exec_properties, features, flaky, imports, legacy_create_init, licenses, local, main, precompile, precompile_invalidation_mode, precompile_optimize_level, precompile_source_retention, pyc_collection, python_version, restricted_to, shard_count, size, srcs_version, stamp, tags, target_compatible_with, testonly, timeout, toolchains, visibility)

Arguments

Attributes
name

Name; required

A unique name for this target.

deps

List of labels; default is []

List of additional libraries to be linked in to the target. See comments about the [`deps` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). These are typically `py_library` rules. Targets that only provide data files used at runtime belong in the `data` attribute.
srcs

List of labels; required

The list of Python source files that are processed to create the target. This includes all your checked-in code and may include generated source files. The `.py` files belong in `srcs` and library targets belong in `deps`. Other binary files that may be needed at run time belong in `data`.
data

List of labels; default is []

The list of files need by this library at runtime. See comments about the [`data` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). There is no `py_embed_data` like there is `cc_embed_data` and `go_embed_data`. This is because Python has a concept of runtime resources.
imports

List of strings; default is []

List of import directories to be added to the PYTHONPATH. Subject to "Make variable" substitution. These import directories will be added for this rule and all rules that depend on it (note: not the rules this rule depends on. Each directory will be added to `PYTHONPATH` by `py_binary` rules that depend on this rule. The strings are repo-runfiles-root relative, Absolute paths (paths that start with `/`) and paths that references a path above the execution root are not allowed and will result in an error.
legacy_create_init

Integer; default is -1

Whether to implicitly create empty `__init__.py` files in the runfiles tree. These are created in every directory containing Python source code or shared libraries, and every parent directory of those directories, excluding the repo root directory. The default, `-1` (auto), means true unless `--incompatible_default_to_explicit_init_py` is used. If false, the user is responsible for creating (possibly empty) `__init__.py` files and adding them to the `srcs` of Python targets as required.
main

Label; default is None

Optional; the name of the source file that is the main entry point of the application. This file must also be listed in `srcs`. If left unspecified, `name`, with `.py` appended, is used instead. If `name` does not match any filename in `srcs`, `main` must be specified.
precompile

String; default is "inherit"

Whether py source files **for this target** should be precompiled. Values: * `inherit`: Determine the value from the {flag}`--precompile` flag. * `enabled`: Compile Python source files at build time. Note that --precompile_add_to_runfiles affects how the compiled files are included into a downstream binary. * `disabled`: Don't compile Python source files at build time. * `if_generated_source`: Compile Python source files, but only if they're a generated file. :::{seealso} * The {flag}`--precompile` flag, which can override this attribute in some cases and will affect all targets when building. * The {obj}`pyc_collection` attribute for transitively enabling precompiling on a per-target basis. * The [Precompiling](precompiling) docs for a guide about using precompiling. :::
precompile_invalidation_mode

String; default is "auto"

How precompiled files should be verified to be up-to-date with their associated source files. Possible values are: * `auto`: The effective value will be automatically determined by other build settings. * `checked_hash`: Use the pyc file if the hash of the source file matches the hash recorded in the pyc file. This is most useful when working with code that you may modify. * `unchecked_hash`: Always use the pyc file; don't check the pyc's hash against the source file. This is most useful when the code won't be modified. For more information on pyc invalidation modes, see https://docs.python.org/3/library/py_compile.html#py_compile.PycInvalidationMode
precompile_optimize_level

Integer; default is 0

The optimization level for precompiled files. For more information about optimization levels, see the `compile()` function's `optimize` arg docs at https://docs.python.org/3/library/functions.html#compile NOTE: The value `-1` means "current interpreter", which will be the interpreter used _at build time when pycs are generated_, not the interpreter used at runtime when the code actually runs.
precompile_source_retention

String; default is "inherit"

Determines, when a source file is compiled, if the source file is kept in the resulting output or not. Valid values are: * `inherit`: Inherit the value from the {flag}`--precompile_source_retention` flag. * `keep_source`: Include the original Python source. * `omit_source`: Don't include the original py source. * `omit_if_generated_source`: Keep the original source if it's a regular source file, but omit it if it's a generated file.
pyc_collection

String; default is "inherit"

Determines whether pyc files from dependencies should be manually included. NOTE: This setting is only useful with {flag}`--precompile_add_to_runfiles=decided_elsewhere`. Valid values are: * `inherit`: Inherit the value from {flag}`--pyc_collection`. * `include_pyc`: Add pyc files from dependencies in the binary (from {obj}`PyInfo.transitive_pyc_files`. * `disabled`: Don't explicitly add pyc files from dependencies. Note that pyc files may still come from dependencies if a target includes them as part of their runfiles (such as when {obj}`--precompile_add_to_runfiles=always` is used).
python_version

String; default is "PY3"

Defunct, unused, does nothing.
srcs_version

String; default is "PY2AND3"

Defunct, unused, does nothing.
stamp

Integer; default is 0

Whether to encode build information into the binary. Possible values: * `stamp = 1`: Always stamp the build information into the binary, even in `--nostamp` builds. **This setting should be avoided**, since it potentially kills remote caching for the binary and any downstream actions that depend on it. * `stamp = 0`: Always replace build information by constant values. This gives good build result caching. * `stamp = -1`: Embedding of build information is controlled by the `--[no]stamp` flag. Stamped binaries are not rebuilt unless their dependencies change. WARNING: Stamping can harm build performance by reducing cache hits and should be avoided if possible.

py_runtime

View rule source
py_runtime(name, bootstrap_template, compatible_with, coverage_tool, deprecation, distribs, exec_compatible_with, exec_properties, features, files, implementation_name, interpreter, interpreter_path, interpreter_version_info, pyc_tag, python_version, restricted_to, stage2_bootstrap_template, stub_shebang, tags, target_compatible_with, testonly, toolchains, visibility, zip_main_template)
Represents a Python runtime used to execute Python code. A `py_runtime` target can represent either a *platform runtime* or an *in-build runtime*. A platform runtime accesses a system-installed interpreter at a known path, whereas an in-build runtime points to an executable target that acts as the interpreter. In both cases, an "interpreter" means any executable binary or wrapper script that is capable of running a Python script passed on the command line, following the same conventions as the standard CPython interpreter. A platform runtime is by its nature non-hermetic. It imposes a requirement on the target platform to have an interpreter located at a specific path. An in-build runtime may or may not be hermetic, depending on whether it points to a checked-in interpreter or a wrapper script that accesses the system interpreter. Example ``` load("@rules_python//python:py_runtime.bzl", "py_runtime") py_runtime( name = "python-2.7.12", files = glob(["python-2.7.12/**"]), interpreter = "python-2.7.12/bin/python", ) py_runtime( name = "python-3.6.0", interpreter_path = "/opt/pyenv/versions/3.6.0/bin/python", ) ```

Arguments

Attributes
name

Name; required

A unique name for this target.

bootstrap_template

Label; default is "@rules_python//python/private:bootstrap_template"

The bootstrap script template file to use. Should have %python_binary%, %workspace_name%, %main%, and %imports%. This template, after expansion, becomes the executable file used to start the process, so it is responsible for initial bootstrapping actions such as finding the Python interpreter, runfiles, and constructing an environment to run the intended Python application. While this attribute is currently optional, it will become required when the Python rules are moved out of Bazel itself. The exact variable names expanded is an unstable API and is subject to change. The API will become more stable when the Python rules are moved out of Bazel itself. See @bazel_tools//tools/python:python_bootstrap_template.txt for more variables.
coverage_tool

Label; default is None

This is a target to use for collecting code coverage information from {rule}`py_binary` and {rule}`py_test` targets. If set, the target must either produce a single file or be an executable target. The path to the single file, or the executable if the target is executable, determines the entry point for the python coverage tool. The target and its runfiles will be added to the runfiles when coverage is enabled. The entry point for the tool must be loadable by a Python interpreter (e.g. a `.py` or `.pyc` file). It must accept the command line arguments of [`coverage.py`](https://coverage.readthedocs.io), at least including the `run` and `lcov` subcommands.
files

List of labels; default is []

For an in-build runtime, this is the set of files comprising this runtime. These files will be added to the runfiles of Python binaries that use this runtime. For a platform runtime this attribute must not be set.
implementation_name

String; default is ""

The Python implementation name (`sys.implementation.name`)
interpreter

Label; default is None

For an in-build runtime, this is the target to invoke as the interpreter. It can be either of: * A single file, which will be the interpreter binary. It's assumed such interpreters are either self-contained single-file executables or any supporting files are specified in `files`. * An executable target. The target's executable will be the interpreter binary. Any other default outputs (`target.files`) and plain files runfiles (`runfiles.files`) will be automatically included as if specified in the `files` attribute. NOTE: the runfiles of the target may not yet be properly respected/propagated to consumers of the toolchain/interpreter, see bazelbuild/rules_python/issues/1612 For a platform runtime (i.e. `interpreter_path` being set) this attribute must not be set.
interpreter_path

String; default is ""

For a platform runtime, this is the absolute path of a Python interpreter on the target platform. For an in-build runtime this attribute must not be set.
interpreter_version_info

Dictionary: String -> String; default is {}

Version information about the interpreter this runtime provides. If not specified, uses {obj}`--python_version` The supported keys match the names for `sys.version_info`. While the input values are strings, most are converted to ints. The supported keys are: * major: int, the major version number * minor: int, the minor version number * micro: optional int, the micro version number * releaselevel: optional str, the release level * serial: optional int, the serial number of the release :::{versionchanged} 0.36.0 {obj}`--python_version` determines the default value. :::
pyc_tag

String; default is ""

Optional string; the tag portion of a pyc filename, e.g. the `cpython-39` infix of `foo.cpython-39.pyc`. See PEP 3147. If not specified, it will be computed from `implementation_name` and `interpreter_version_info`. If no pyc_tag is available, then only source-less pyc generation will function correctly.
python_version

String; default is "PY3"

Whether this runtime is for Python major version 2 or 3. Valid values are `"PY2"` and `"PY3"`. The default value is controlled by the `--incompatible_py3_is_default` flag. However, in the future this attribute will be mandatory and have no default value.
stage2_bootstrap_template

Label; default is "@rules_python//python/private:stage2_bootstrap_template"

The template to use when two stage bootstrapping is enabled :::{seealso} {obj}`PyRuntimeInfo.stage2_bootstrap_template` and {obj}`--bootstrap_impl` :::
stub_shebang

String; default is "#!/usr/bin/env python3"

"Shebang" expression prepended to the bootstrapping Python stub script used when executing {rule}`py_binary` targets. See https://github.com/bazelbuild/bazel/issues/8685 for motivation. Does not apply to Windows.
zip_main_template

Label; default is "@rules_python//python/private:zip_main_template"

The template to use for a zip's top-level `__main__.py` file. This becomes the entry point executed when `python foo.zip` is run. :::{seealso} The {obj}`PyRuntimeInfo.zip_main_template` field. :::