---
title: 'Python Rules'
---

## Rules

* [py\_binary](#py_binary)
* [py\_library](#py_library)
* [py\_test](#py_test)
* [py\_runtime](#py_runtime)

## py\_binary

[View rule sourceopen\_in\_new](https://github.com/bazelbuild/rules_python/tree/0.40.0/python/private/py_binary_rule.bzl)

```
py_binary(name, deps, srcs, data, args, aspect_hints, compatible_with, config_settings, deprecation, distribs, env, exec_compatible_with, exec_group_compatible_with, exec_properties, features, imports, interpreter_args, legacy_create_init, licenses, main, main_module, output_licenses, package_metadata, precompile, precompile_invalidation_mode, precompile_optimize_level, precompile_source_retention, pyc_collection, pyi_deps, pyi_srcs, python_version, restricted_to, srcs_version, stamp, tags, target_compatible_with, testonly, toolchains, visibility)
```

### Arguments

| Attributes | |
| --- | --- |
| `name` | [Name](/versions/9.0.0/concepts/labels#target-names); required  A unique name for this target. |
| `deps` | List of [labels](/versions/9.0.0/concepts/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/versions/9.0.0/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. :::{note} The order of this list can matter because it affects the order that information from dependencies is merged in, which can be relevant depending on the ordering mode of depsets that are merged. \* {obj}`PyInfo.venv\_symlinks` uses default ordering. See {obj}`PyInfo` for more information about the ordering of its depsets and how its fields are merged. ::: |
| `srcs` | List of [labels](/versions/9.0.0/concepts/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](/versions/9.0.0/concepts/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/versions/9.0.0/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. |
| `config_settings` | Dictionary: [label](/versions/9.0.0/concepts/labels) -> String; default is `{}` Config settings to change for this target. The keys are labels for settings, and the values are strings for the new value to use. Pass `Label` objects or canonical label strings for the keys to ensure they resolve as expected (canonical labels start with `@@` and can be obtained by calling `str(Label(...))`). Most `@rules\_python//python/config\_setting` settings can be used here, which allows, for example, making only a certain `py\_binary` use {obj}`--boostrap\_impl=script`. Additional or custom config settings can be registered using the {obj}`add\_transition\_setting` API. This allows, for example, forcing a particular CPU, or defining a custom setting that `select()` uses elsewhere to pick between `pip.parse` hubs. See the [How to guide on multiple versions of a library] for a more concrete example. :::{note} These values are transitioned on, so will affect the analysis graph and the associated memory overhead. The more unique configurations in your overall build, the more memory and (often unnecessary) re-analysis and re-building can occur. See https://bazel.build/extending/config#memory-performance-considerations for more information about risks and considerations. ::: :::{versionadded} 1.7.0 ::: |
| `distribs` | List of strings; default is `[]` |
| `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. |
| `interpreter_args` | List of strings; default is `[]` Arguments that are only applicable to the interpreter. The args an interpreter supports are specific to the interpreter. For CPython, see https://docs.python.org/3/using/cmdline.html. :::{note} Only supported for {obj}`--bootstrap\_impl=script`. Ignored otherwise. ::: :::{seealso} The {any}`RULES\_PYTHON\_ADDITIONAL\_INTERPRETER\_ARGS` environment variable ::: :::{versionadded} 1.3.0 ::: |
| `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](/versions/9.0.0/concepts/labels); 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. This is mutually exclusive with {obj}`main\_module`. |
| `main_module` | String; default is `""` Module name to execute as the main program. When set, `srcs` is not required, and it is assumed the module is provided by a dependency. See https://docs.python.org/3/using/cmdline.html#cmdoption-m for more information about running modules as the main program. This is mutually exclusive with {obj}`main`. :::{versionadded} 1.3.0 ::: :::{versionchanged} 1.7.0 Support added for {obj}`--bootstrap\_impl=system\_python`. ::: |
| `precompile` | String; default is `"inherit"` Whether py source files \*\*for this target\*\* should be precompiled. Values: \* `inherit`: Allow the downstream binary decide if precompiled files are used. \* `enabled`: Compile Python source files at build time. \* `disabled`: Don't compile Python source files at build time. :::{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. |
| `pyc_collection` | String; default is `"inherit"` Determines whether pyc files from dependencies should be manually included. Valid values are: \* `inherit`: Inherit the value from {flag}`--precompile`. \* `include\_pyc`: Add implicitly generated pyc files from dependencies. i.e. pyc files for targets that specify {attr}`precompile="inherit"`. \* `disabled`: Don't add implicitly generated pyc files. Note that pyc files may still come from dependencies that enable precompiling at the target level. |
| `pyi_deps` | List of [labels](/versions/9.0.0/concepts/labels); default is `[]` Dependencies providing type definitions the library needs. These are dependencies that satisfy imports guarded by `typing.TYPE\_CHECKING`. These are build-time only dependencies and not included as part of a runnable program (packaging rules may include them, however). :::{versionadded} 1.1.0 ::: |
| `pyi_srcs` | List of [labels](/versions/9.0.0/concepts/labels); default is `[]` Type definition files for the library. These are typically `.pyi` files, but other file types for type-checker specific formats are allowed. These files are build-time only dependencies and not included as part of a runnable program (packaging rules may include them, however). :::{versionadded} 1.1.0 ::: |
| `python_version` | String; default is `""` The Python version this target should use. The value should be in `X.Y` or `X.Y.Z` (or compatible) format. If empty or unspecified, the incoming configuration's {obj}`--python\_version` flag is inherited. For backwards compatibility, the values `PY2` and `PY3` are accepted, but treated as an empty/unspecified value. :::{note} In order for the requested version to be used, there must be a toolchain configured to match the Python version. If there isn't, then it may be silently ignored, or an error may occur, depending on the toolchain configuration. ::: :::{versionchanged} 1.1.0 This attribute was changed from only accepting `PY2` and `PY3` values to accepting arbitrary Python versions. ::: |
| `srcs_version` | String; default is `""` 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 sourceopen\_in\_new](https://github.com/bazelbuild/rules_python/tree/0.40.0/python/private/py_library_rule.bzl)

```
py_library(name, deps, srcs, data, aspect_hints, compatible_with, deprecation, distribs, exec_compatible_with, exec_group_compatible_with, exec_properties, experimental_venvs_site_packages, features, imports, licenses, package_metadata, precompile, precompile_invalidation_mode, precompile_optimize_level, precompile_source_retention, pyi_deps, pyi_srcs, 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.
:::{versionchanged} 0.37.0
Source files are no longer added to the runfiles directly.
:::

### Arguments

| Attributes | |
| --- | --- |
| `name` | [Name](/versions/9.0.0/concepts/labels#target-names); required  A unique name for this target. |
| `deps` | List of [labels](/versions/9.0.0/concepts/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/versions/9.0.0/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. :::{note} The order of this list can matter because it affects the order that information from dependencies is merged in, which can be relevant depending on the ordering mode of depsets that are merged. \* {obj}`PyInfo.venv\_symlinks` uses default ordering. See {obj}`PyInfo` for more information about the ordering of its depsets and how its fields are merged. ::: |
| `srcs` | List of [labels](/versions/9.0.0/concepts/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](/versions/9.0.0/concepts/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/versions/9.0.0/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. |
| `distribs` | List of strings; default is `[]` |
| `experimental_venvs_site_packages` | [Label](/versions/9.0.0/concepts/labels); default is `None` \*\*INTERNAL ATTRIBUTE. SHOULD ONLY BE SET BY rules\_python-INTERNAL CODE.\*\* :::{include} /\_includes/experimental\_api.md ::: A flag that decides whether the library should treat its sources as a site-packages layout. When the flag is `yes`, then the `srcs` files are treated as a site-packages layout that is relative to the `imports` attribute. The `imports` attribute can have only a single element. It is a repo-relative runfiles path. For example, in the `my/pkg/BUILD.bazel` file, given `srcs=["site-packages/foo/bar.py"]`, specifying `imports=["my/pkg/site-packages"]` means `foo/bar.py` is the file path under the binary's venv site-packages directory that should be made available (i.e. `import foo.bar` will work). `\_\_init\_\_.py` files are treated specially to provide basic support for [implicit namespace packages]( https://packaging.python.org/en/latest/guides/packaging-namespace-packages/#native-namespace-packages). However, the \*content\* of the files cannot be taken into account, merely their presence or absence. Stated another way: [pkgutil-style namespace packages]( https://packaging.python.org/en/latest/guides/packaging-namespace-packages/#pkgutil-style-namespace-packages) won't be understood as namespace packages; they'll be seen as regular packages. This will likely lead to conflicts with other targets that contribute to the namespace. :::{seealso} This attributes populates {obj}`PyInfo.venv\_symlinks`. ::: :::{versionadded} 1.4.0 ::: :::{versionchanged} 1.5.0 The topological order has been removed and if 2 different versions of the same PyPI package are observed, the behaviour has no guarantees except that it is deterministic and that only one package version will be included. ::: |
| `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`: Allow the downstream binary decide if precompiled files are used. \* `enabled`: Compile Python source files at build time. \* `disabled`: Don't compile Python source files at build time. :::{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. |
| `pyi_deps` | List of [labels](/versions/9.0.0/concepts/labels); default is `[]` Dependencies providing type definitions the library needs. These are dependencies that satisfy imports guarded by `typing.TYPE\_CHECKING`. These are build-time only dependencies and not included as part of a runnable program (packaging rules may include them, however). :::{versionadded} 1.1.0 ::: |
| `pyi_srcs` | List of [labels](/versions/9.0.0/concepts/labels); default is `[]` Type definition files for the library. These are typically `.pyi` files, but other file types for type-checker specific formats are allowed. These files are build-time only dependencies and not included as part of a runnable program (packaging rules may include them, however). :::{versionadded} 1.1.0 ::: |
| `srcs_version` | String; default is `""` Defunct, unused, does nothing. |

## py\_test

[View rule sourceopen\_in\_new](https://github.com/bazelbuild/rules_python/tree/0.40.0/python/private/py_test_rule.bzl)

```
py_test(name, deps, srcs, data, args, aspect_hints, compatible_with, config_settings, deprecation, distribs, env, env_inherit, exec_compatible_with, exec_group_compatible_with, exec_properties, features, flaky, imports, interpreter_args, legacy_create_init, licenses, local, main, main_module, package_metadata, precompile, precompile_invalidation_mode, precompile_optimize_level, precompile_source_retention, pyc_collection, pyi_deps, pyi_srcs, python_version, restricted_to, shard_count, size, srcs_version, stamp, tags, target_compatible_with, testonly, timeout, toolchains, visibility)
```

### Arguments

| Attributes | |
| --- | --- |
| `name` | [Name](/versions/9.0.0/concepts/labels#target-names); required  A unique name for this target. |
| `deps` | List of [labels](/versions/9.0.0/concepts/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/versions/9.0.0/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. :::{note} The order of this list can matter because it affects the order that information from dependencies is merged in, which can be relevant depending on the ordering mode of depsets that are merged. \* {obj}`PyInfo.venv\_symlinks` uses default ordering. See {obj}`PyInfo` for more information about the ordering of its depsets and how its fields are merged. ::: |
| `srcs` | List of [labels](/versions/9.0.0/concepts/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](/versions/9.0.0/concepts/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/versions/9.0.0/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. |
| `config_settings` | Dictionary: [label](/versions/9.0.0/concepts/labels) -> String; default is `{}` Config settings to change for this target. The keys are labels for settings, and the values are strings for the new value to use. Pass `Label` objects or canonical label strings for the keys to ensure they resolve as expected (canonical labels start with `@@` and can be obtained by calling `str(Label(...))`). Most `@rules\_python//python/config\_setting` settings can be used here, which allows, for example, making only a certain `py\_binary` use {obj}`--boostrap\_impl=script`. Additional or custom config settings can be registered using the {obj}`add\_transition\_setting` API. This allows, for example, forcing a particular CPU, or defining a custom setting that `select()` uses elsewhere to pick between `pip.parse` hubs. See the [How to guide on multiple versions of a library] for a more concrete example. :::{note} These values are transitioned on, so will affect the analysis graph and the associated memory overhead. The more unique configurations in your overall build, the more memory and (often unnecessary) re-analysis and re-building can occur. See https://bazel.build/extending/config#memory-performance-considerations for more information about risks and considerations. ::: :::{versionadded} 1.7.0 ::: |
| `distribs` | List of strings; default is `[]` |
| `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. |
| `interpreter_args` | List of strings; default is `[]` Arguments that are only applicable to the interpreter. The args an interpreter supports are specific to the interpreter. For CPython, see https://docs.python.org/3/using/cmdline.html. :::{note} Only supported for {obj}`--bootstrap\_impl=script`. Ignored otherwise. ::: :::{seealso} The {any}`RULES\_PYTHON\_ADDITIONAL\_INTERPRETER\_ARGS` environment variable ::: :::{versionadded} 1.3.0 ::: |
| `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](/versions/9.0.0/concepts/labels); 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. This is mutually exclusive with {obj}`main\_module`. |
| `main_module` | String; default is `""` Module name to execute as the main program. When set, `srcs` is not required, and it is assumed the module is provided by a dependency. See https://docs.python.org/3/using/cmdline.html#cmdoption-m for more information about running modules as the main program. This is mutually exclusive with {obj}`main`. :::{versionadded} 1.3.0 ::: :::{versionchanged} 1.7.0 Support added for {obj}`--bootstrap\_impl=system\_python`. ::: |
| `precompile` | String; default is `"inherit"` Whether py source files \*\*for this target\*\* should be precompiled. Values: \* `inherit`: Allow the downstream binary decide if precompiled files are used. \* `enabled`: Compile Python source files at build time. \* `disabled`: Don't compile Python source files at build time. :::{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. |
| `pyc_collection` | String; default is `"inherit"` Determines whether pyc files from dependencies should be manually included. Valid values are: \* `inherit`: Inherit the value from {flag}`--precompile`. \* `include\_pyc`: Add implicitly generated pyc files from dependencies. i.e. pyc files for targets that specify {attr}`precompile="inherit"`. \* `disabled`: Don't add implicitly generated pyc files. Note that pyc files may still come from dependencies that enable precompiling at the target level. |
| `pyi_deps` | List of [labels](/versions/9.0.0/concepts/labels); default is `[]` Dependencies providing type definitions the library needs. These are dependencies that satisfy imports guarded by `typing.TYPE\_CHECKING`. These are build-time only dependencies and not included as part of a runnable program (packaging rules may include them, however). :::{versionadded} 1.1.0 ::: |
| `pyi_srcs` | List of [labels](/versions/9.0.0/concepts/labels); default is `[]` Type definition files for the library. These are typically `.pyi` files, but other file types for type-checker specific formats are allowed. These files are build-time only dependencies and not included as part of a runnable program (packaging rules may include them, however). :::{versionadded} 1.1.0 ::: |
| `python_version` | String; default is `""` The Python version this target should use. The value should be in `X.Y` or `X.Y.Z` (or compatible) format. If empty or unspecified, the incoming configuration's {obj}`--python\_version` flag is inherited. For backwards compatibility, the values `PY2` and `PY3` are accepted, but treated as an empty/unspecified value. :::{note} In order for the requested version to be used, there must be a toolchain configured to match the Python version. If there isn't, then it may be silently ignored, or an error may occur, depending on the toolchain configuration. ::: :::{versionchanged} 1.1.0 This attribute was changed from only accepting `PY2` and `PY3` values to accepting arbitrary Python versions. ::: |
| `srcs_version` | String; default is `""` 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 sourceopen\_in\_new](https://github.com/bazelbuild/rules_python/tree/0.40.0/python/private/py_runtime_rule.bzl)

```
py_runtime(name, abi_flags, aspect_hints, bootstrap_template, compatible_with, coverage_tool, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, files, implementation_name, interpreter, interpreter_path, interpreter_version_info, package_metadata, pyc_tag, python_version, restricted_to, site_init_template, stage2_bootstrap_template, stub_shebang, supports_build_time_venv, 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](/versions/9.0.0/concepts/labels#target-names); required  A unique name for this target. |
| `abi_flags` | String; default is `""` The runtime's ABI flags, i.e. `sys.abiflags`. If not set, then it will be set based on flags. |
| `bootstrap_template` | [Label](/versions/9.0.0/concepts/labels); 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](/versions/9.0.0/concepts/labels); 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](/versions/9.0.0/concepts/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 `"cpython"` The Python implementation name (`sys.implementation.name`) |
| `interpreter` | [Label](/versions/9.0.0/concepts/labels); 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 bazel-contrib/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. |
| `site_init_template` | [Label](/versions/9.0.0/concepts/labels); default is `"@rules_python//python/private:site_init_template"` The template to use for the binary-specific site-init hook run by the interpreter at startup. :::{versionadded} 0.41.0 ::: |
| `stage2_bootstrap_template` | [Label](/versions/9.0.0/concepts/labels); 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. |
| `supports_build_time_venv` | Boolean; default is `True` Whether this runtime supports virtualenvs created at build time. See {obj}`PyRuntimeInfo.supports\_build\_time\_venv` for docs. :::{versionadded} 1.5.0 ::: |
| `zip_main_template` | [Label](/versions/9.0.0/concepts/labels); 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. ::: |