• Stars
    star
    521
  • Rank 84,952 (Top 2 %)
  • Language Starlark
  • License
    Apache License 2.0
  • Created about 7 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Bazel Python Rules

Python Rules for Bazel

  • Postsubmit Build status
  • Postsubmit + Current Bazel Incompatible Flags Build status

Overview

This repository is the home of the core Python rules -- py_library, py_binary, py_test, py_proto_library, and related symbols that provide the basis for Python support in Bazel. It also contains package installation rules for integrating with PyPI and other package indices. Documentation lives in the docs/ directory and in the Bazel Build Encyclopedia.

Currently the core rules are bundled with Bazel itself, and the symbols in this repository are simple aliases. However, in the future the rules will be migrated to Starlark and debundled from Bazel. Therefore, the future-proof way to depend on Python rules is via this repository. SeeMigrating from the Bundled Rules below.

The core rules are stable. Their implementation in Bazel is subject to Bazel's backward compatibility policy. Once they are fully migrated to rules_python, they may evolve at a different rate, but this repository will still follow semantic versioning.

The package installation rules (pip_install, pip_parse etc.) are less stable. We may make breaking changes as they evolve.

This repository is maintained by the Bazel community. Neither Google, nor the Bazel team, provides support for the code. However, this repository is part of the test suite used to vet new Bazel releases. See the How to contribute page for information on our development workflow.

bzlmod support

  • Status: Beta
  • Full Feature Parity: No

See Bzlmod support for more details.

Getting started

The next two sections cover using rules_python with bzlmod and the older way of configuring bazel with a WORKSPACE file.

Using bzlmod

NOTE: bzlmod support is still experimental; APIs subject to change.

To import rules_python in your project, you first need to add it to your MODULE.bazel file, using the snippet provided in the release you choose.

Once the dependency is added, a Python toolchain will be automatically registered and you'll be able to create runnable programs and tests.

Toolchain registration with bzlmod

NOTE: bzlmod support is still experimental; APIs subject to change.

A default toolchain is automatically configured for by depending on rules_python. Note, however, the version used tracks the most recent Python release and will change often.

If you want to register specific Python versions, then use python.toolchain() for each version you need:

python = use_extension("@rules_python//python:extensions.bzl", "python")

python.toolchain(
    python_version = "3.9",
)

Using pip with bzlmod

NOTE: bzlmod support is still experimental; APIs subject to change.

To use dependencies from PyPI, the pip.parse() extension is used to convert a requirements file into Bazel dependencies.

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

interpreter = use_extension("@rules_python//python/extensions:interpreter.bzl", "interpreter")
interpreter.install(
    name = "interpreter",
    python_name = "python_3_9",
)
use_repo(interpreter, "interpreter")

pip = use_extension("@rules_python//python/extensions:pip.bzl", "pip")
pip.parse(
    hub_name = "pip",
    python_interpreter_target = "@interpreter//:python",
    requirements_lock = "//:requirements_lock.txt",
    requirements_windows = "//:requirements_windows.txt",
)
use_repo(pip, "pip")

For more documentation see the bzlmod examples under the examples folder.

Using a WORKSPACE file

To import rules_python in your project, you first need to add it to your WORKSPACE file, using the snippet provided in the release you choose

To depend on a particular unreleased version, you can do:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

rules_python_version = "740825b7f74930c62f44af95c9a4c1bd428d2c53" # Latest @ 2021-06-23

http_archive(
    name = "rules_python",
    # Bazel will print the proper value to add here during the first build.
    # sha256 = "FIXME",
    strip_prefix = "rules_python-{}".format(rules_python_version),
    url = "https://github.com/bazelbuild/rules_python/archive/{}.zip".format(rules_python_version),
)

Toolchain registration

To register a hermetic Python toolchain rather than rely on a system-installed interpreter for runtime execution, you can add to the WORKSPACE file:

load("@rules_python//python:repositories.bzl", "python_register_toolchains")

python_register_toolchains(
    name = "python3_9",
    # Available versions are listed in @rules_python//python:versions.bzl.
    # We recommend using the same version your team is already standardized on.
    python_version = "3.9",
)

load("@python3_9//:defs.bzl", "interpreter")

load("@rules_python//python:pip.bzl", "pip_parse")

pip_parse(
    ...
    python_interpreter_target = interpreter,
    ...
)

After registration, your Python targets will use the toolchain's interpreter during execution, but a system-installed interpreter is still used to 'bootstrap' Python targets (see #691). You may also find some quirks while using this toolchain. Please refer to python-build-standalone documentation's Quirks section for details.

Toolchain usage in other rules

Python toolchains can be utilised in other bazel rules, such as genrule(), by adding the toolchains=["@rules_python//python:current_py_toolchain"] attribute. The path to the python interpreter can be obtained by using the $(PYTHON2) and $(PYTHON3) "Make" Variables. See the test_current_py_toolchain target for an example.

"Hello World"

Once you've imported the rule set into your WORKSPACE using any of these methods, you can then load the core rules in your BUILD files with:

load("@rules_python//python:defs.bzl", "py_binary")

py_binary(
  name = "main",
  srcs = ["main.py"],
)

Using the package installation rules

Usage of the packaging rules involves two main steps.

  1. Installing third_party packages
  2. Using third_party packages as dependencies

The package installation rules create two kinds of repositories: A central external repo that holds downloaded wheel files, and individual external repos for each wheel's extracted contents. Users only need to interact with the central external repo; the wheel repos are essentially an implementation detail. The central external repo provides a WORKSPACE macro to create the wheel repos, as well as a function, requirement(), for use in BUILD files that translates a pip package name into the label of a py_library target in the appropriate wheel repo.

Installing third_party packages

Using bzlmod

To add pip dependencies to your MODULE.bazel file, use the pip.parse extension, and call it to create the central external repo and individual wheel external repos.

pip.parse(
    hub_name = "my_deps",
    requirements_lock = "//:requirements_lock.txt",
)

use_repo(pip, "my_deps")

Using a WORKSPACE file

To add pip dependencies to your WORKSPACE, load the pip_parse function, and call it to create the central external repo and individual wheel external repos.

load("@rules_python//python:pip.bzl", "pip_parse")

# Create a central repo that knows about the dependencies needed from
# requirements_lock.txt.
pip_parse(
   name = "my_deps",
   requirements_lock = "//path/to:requirements_lock.txt",
)
# Load the starlark macro which will define your dependencies.
load("@my_deps//:requirements.bzl", "install_deps")
# Call it to define repos for your requirements.
install_deps()

pip rules

Note that since pip_parse is a repository rule and therefore executes pip at WORKSPACE-evaluation time, Bazel has no information about the Python toolchain and cannot enforce that the interpreter used to invoke pip matches the interpreter used to run py_binary targets. By default, pip_parse uses the system command "python3". This can be overridden by passing the python_interpreter attribute or python_interpreter_target attribute to pip_parse.

You can have multiple pip_parses in the same workspace. This will create multiple external repos that have no relation to one another, and may result in downloading the same wheels multiple times.

As with any repository rule, if you would like to ensure that pip_parse is re-executed in order to pick up a non-hermetic change to your environment (e.g., updating your system python interpreter), you can force it to re-execute by running bazel sync --only [pip_parse name].

Note: The pip_install rule is deprecated. pip_parse offers identical functionality and both pip_install and pip_parse now have the same implementation. The name pip_install may be removed in a future version of the rules. The maintainers have taken all reasonable efforts to faciliate a smooth transition, but some users of pip_install will need to replace their existing requirements.txt with a fully resolved set of dependencies using a tool such as pip-tools or the compile_pip_requirements repository rule.

Using third_party packages as dependencies

Each extracted wheel repo contains a py_library target representing the wheel's contents. There are two ways to access this library. The first is using the requirement() function defined in the central repo's //:requirements.bzl file. This function maps a pip package name to a label:

load("@my_deps//:requirements.bzl", "requirement")

py_library(
    name = "mylib",
    srcs = ["mylib.py"],
    deps = [
        ":myotherlib",
        requirement("some_pip_dep"),
        requirement("another_pip_dep"),
    ]
)

The reason requirement() exists is that the pattern for the labels, while not expected to change frequently, is not guaranteed to be stable. Using requirement() ensures that you do not have to refactor your BUILD files if the pattern changes.

On the other hand, using requirement() has several drawbacks; see this issue for an enumeration. If you don't want to use requirement() then you can instead use the library labels directly. For pip_parse the labels are of the form

@{name}_{package}//:pkg

Here name is the name attribute that was passed to pip_parse and package is the pip package name with characters that are illegal in Bazel label names (e.g. -, .) replaced with _. If you need to update name from "old" to "new", then you can run the following buildozer command:

buildozer 'substitute deps @old_([^/]+)//:pkg @new_${1}//:pkg' //...:*

For pip_install the labels are instead of the form

@{name}//pypi__{package}

'Extras' dependencies

Any 'extras' specified in the requirements lock-file will be automatically added as transitive dependencies of the package. In the example above, you'd just put requirement("useful_dep").

Consuming Wheel Dists Directly

If you need to depend on the wheel dists themselves, for instance to pass them to some other packaging tool, you can get a handle to them with the whl_requirement macro. For example:

filegroup(
    name = "whl_files",
    data = [
        whl_requirement("boto3"),
    ]
)

Migrating from the bundled rules

The core rules are currently available in Bazel as built-in symbols, but this form is deprecated. Instead, you should depend on rules_python in your WORKSPACE file and load the Python rules from @rules_python//python:defs.bzl.

A buildifier fix is available to automatically migrate BUILD and .bzl files to add the appropriate load() statements and rewrite uses of native.py_*.

# Also consider using the -r flag to modify an entire workspace.
buildifier --lint=fix --warnings=native-py <files>

Currently the WORKSPACE file needs to be updated manually as per Getting started above.

Note that Starlark-defined bundled symbols underneath @bazel_tools//tools/python are also deprecated. These are not yet rewritten by buildifier.

More Repositories

1

bazel

a fast, scalable, multi-language and extensible build system
Java
22,794
star
2

starlark

Starlark Language
Starlark
2,435
star
3

bazelisk

A user-friendly launcher for Bazel.
Go
2,060
star
4

rules_go

Go rules for Bazel
Go
1,356
star
5

bazel-gazelle

Gazelle is a Bazel build file generator for Bazel projects. It natively supports Go and protobuf, and it may be extended to support new languages and custom rule sets.
Go
1,156
star
6

rules_docker

Rules for building and handling Docker images with Bazel
Starlark
1,074
star
7

buildtools

A bazel BUILD file formatter and editor
Go
1,007
star
8

examples

Examples for Bazel
Starlark
831
star
9

intellij

IntelliJ plugin for Bazel projects
Java
762
star
10

rules_rust

Rust rules for Bazel
Starlark
660
star
11

bazel-buildfarm

Bazel remote caching and execution service
Java
650
star
12

tulsi

An Xcode Project Generator For Bazel
Swift
547
star
13

rules_apple

Bazel rules to build apps for Apple platforms.
Starlark
509
star
14

bazel-watcher

Tools for building Bazel targets when source files change.
Go
440
star
15

bazel-skylib

Common useful functions and rules for Bazel
Starlark
393
star
16

sandboxfs

A virtual file system for sandboxing
Rust
371
star
17

rules_scala

Scala rules for Bazel
Starlark
360
star
18

rules_kotlin

Bazel rules for Kotlin
Kotlin
331
star
19

remote-apis

An API for caching and execution of actions on a remote system.
Go
328
star
20

rules_swift

Bazel rules to build Swift on Apple and Linux platforms
Starlark
311
star
21

rules_k8s

This repository contains rules for interacting with Kubernetes configurations / clusters.
Starlark
289
star
22

rules_typescript

MOVED to https://github.com/bazelbuild/rules_nodejs/tree/3.x/third_party/github.com/bazelbuild/rules_typescript
TypeScript
275
star
23

continuous-integration

Bazel's Continuous Integration Setup
Python
258
star
24

bazel-central-registry

The central registry of Bazel modules for the Bzlmod external dependency system.
Starlark
247
star
25

rules_pkg

Bazel rules for creating packages of many types (zip, tar, deb, rpm, ...)
Starlark
225
star
26

rules_cc

C++ Rules for Bazel
Starlark
184
star
27

bazel-toolchains

Repository that hosts Bazel toolchain configs for remote execution and related support tools.
Go
183
star
28

rules_android

Android rules for Bazel
Starlark
175
star
29

rules_proto

Protocol buffer rules for Bazel
Starlark
163
star
30

rules_closure

Closure rules for Bazel
Java
153
star
31

vim-bazel

Vim support for Bazel
Vim Script
144
star
32

platforms

Constraint values for specifying platforms and toolchains
Starlark
108
star
33

stardoc

Stardoc: Starlark Documentation Generator
Java
107
star
34

proposals

Index of all Bazel proposals and design documents
106
star
35

rules_webtesting

Bazel rules to allow testing against a browser with WebDriver.
Go
96
star
36

apple_support

Apple support for Bazel rules
Starlark
83
star
37

emacs-bazel-mode

Emacs mode for Bazel
Emacs Lisp
80
star
38

rules_license

Starlark
77
star
39

rules_java

Java rules for Bazel
Starlark
72
star
40

reclient

Go
65
star
41

setup-bazelisk

Set up your GitHub Actions workflow with a specific version of Bazelisk
TypeScript
56
star
42

rules_sass

Sass rules for Bazel
Starlark
51
star
43

remote-apis-sdks

This repository contains client libraries for the Remote Execution API https://github.com/bazelbuild/remote-apis
Go
48
star
44

bazel-federation

Starlark
47
star
45

skydoc

Documentation generator for Skylark
Python
46
star
46

migration-tooling

Migration tools for Bazel
Java
44
star
47

codelabs

Shell
39
star
48

BUILD_file_generator

Generate BUILD files for your Java files
Java
39
star
49

eclipse

Eclipse For Bazel (deprecated, see https://github.com/salesforce/bazel-eclipse instead)
Java
32
star
50

bazel-integration-testing

Framework for integration tests that call Bazel
Java
32
star
51

rules_appengine

AppEngine rules for Bazel
Starlark
30
star
52

rules_android_ndk

Starlark
29
star
53

tools_remote

Java
28
star
54

bazel-bench

Benchmarking tool for bazel
Python
27
star
55

vim-ft-bzl

Vim Script
27
star
56

rules_perl

Perl rules for Bazel
Starlark
25
star
57

tools_android

Tools for use with building Android apps with Bazel
Starlark
24
star
58

homebrew-tap

This repository contains a collection of Homebrew (aka, Brew) "formulae" for Bazel
24
star
59

rules_d

D rules for Bazel
Starlark
24
star
60

bazel-blog

Content of the Bazel blog
HTML
20
star
61

bzlmod

Go
20
star
62

rules_testing

Starlark testing framework and utility libraries
Starlark
20
star
63

rules_gwt

Bazel rules for GWT
Starlark
19
star
64

bazel-website

Website for Bazel, a fast, scalable, multi-language and extensible build system
HTML
17
star
65

bazelcon

Artifacts from BazelCon
15
star
66

java_tools

Python
12
star
67

rules_groovy

Groovy rules for Bazel
Starlark
11
star
68

rules_postcss

PostCSS rules for Bazel
Starlark
10
star
69

rules_platform

Starlark
8
star
70

bazel_metrics

Python
7
star
71

community

Resources for community management efforts, such as SIGs
6
star
72

rules_angular

OBSOLETE see https://github.com/angular/angular/tree/master/packages/bazel
Python
5
star
73

gmaven_rules

This repository is deprecated. Please instead use https://github.com/bazelbuild/rules_jvm_external
Python
3
star
74

rules_utp

Starlark
2
star
75

.allstar

1
star
76

.github

1
star
77

bazel-worker-api

Java
1
star
78

build-event-stream

1
star
79

rules_sh

1
star