• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. _docs-python-build:
2
3======================
4Pigweed's Python build
5======================
6Pigweed uses a custom GN-based build system to manage its Python code. The
7Pigweed Python build supports packaging, installation, and distribution of
8interdependent local Python packages. It also provides for fast, incremental
9static analysis and test running suitable for live use during development (e.g.
10with :ref:`module-pw_watch`) or in continuous integration.
11
12Pigweed's Python code is exclusively managed by GN, but the GN-based build may
13be used alongside CMake, Bazel, or any other build system. Pigweed's environment
14setup uses GN to set up the initial Python environment, regardless of the final
15build system. As needed, non-GN projects can declare just their Python packages
16in GN.
17
18Background
19==========
20Developing software involves much more than writing source code. Software needs
21to be compiled, executed, tested, analyzed, packaged, and deployed. As projects
22grow beyond a few files, these tasks become impractical to manage manually.
23Build systems automate these auxiliary tasks of software development, making it
24possible to build larger, more complex systems quickly and robustly.
25
26Python is an interpreted language, but it shares most build automation concerns
27with other languages. Pigweed uses Python extensively and must to address these
28needs for itself and its users.
29
30Existing solutions
31==================
32The Python programming langauge does not have an official build automation
33system. However, there are numerous Python-focused build automation tools with
34varying degrees of adoption. See the `Python Wiki
35<https://wiki.python.org/moin/ConfigurationAndBuildTools>`_ for examples.
36
37A few Python tools have become defacto standards, including `setuptools
38<https://pypi.org/project/setuptools/>`_, `wheel
39<https://pypi.org/project/wheel/>`_, and `pip <https://pypi.org/project/pip/>`_.
40These essential tools address key aspects of Python packaging and distribution,
41but are not intended for general build automation. Tools like `PyBuilder
42<https://pybuilder.io/>`_ and `tox <https://tox.readthedocs.io/en/latest/>`_
43provide more general build automation for Python.
44
45The `Bazel <http://bazel.build/>`_ build system has first class support for
46Python and other languages used by Pigweed, including protocol buffers.
47
48Challenges
49==========
50Pigweed's use of Python is different from many other projects. Pigweed is a
51multi-language, modular project. It serves both as a library or middleware and
52as a development environment.
53
54This section describes Python build automation challenges encountered by
55Pigweed.
56
57Dependencies
58------------
59Pigweed is organized into distinct modules. In Python, each module is a separate
60package, potentially with dependencies on other local or `PyPI
61<https://pypi.org/>`_ packages.
62
63The basic Python packaging tools lack dependency tracking for local packages.
64For example, a package's ``setup.py`` or ``setup.cfg`` lists all of
65its dependencies, but ``pip`` is not aware of local packages until they are
66installed. Packages must be installed with their dependencies taken into
67account, in topological sorted order.
68
69To work around this, one could set up a private `PyPI server
70<https://pypi.org/project/pypiserver/>`_ instance, but this is too cumbersome
71for daily development and incompatible with editable package installation.
72
73Testing
74-------
75Tests are crucial to having a healthy, maintainable codebase. While they take
76some initial work to write, the time investment pays for itself many times over
77by contributing to the long-term resilience of a codebase. Despite their
78benefit, developers don't always take the time to write tests. Any barriers to
79writing and running tests result in fewer tests and consequently more fragile,
80bug-prone codebases.
81
82There are lots of great Python libraries for testing, such as
83`unittest <https://docs.python.org/3/library/unittest.html>`_ and
84`pytest <https://docs.pytest.org/en/stable/>`_. These tools make it easy to
85write and execute individual Python tests, but are not well suited for managing
86suites of interdependent tests in a large project. Writing a test with these
87utilities does not automatically run them or keep running them as the codebase
88changes.
89
90Static analysis
91---------------
92Various static analysis tools exist for Python. Two widely used, powerful tools
93are `Pylint <https://www.pylint.org/>`_ and `Mypy <http://mypy-lang.org/>`_.
94Using these tools improves code quality, as they catch bugs, encourage good
95design practices, and enforce a consistent coding style. As with testing,
96barriers to running static analysis tools cause many developers to skip them.
97Some developers may not even be aware of these tools.
98
99Deploying static analysis tools to a codebase like Pigweed has some challenges.
100Mypy and Pylint are simple to run, but they are extremely slow. Ideally, these
101tools would be run constantly during development, but only on files that change.
102These tools do not have built-in support for incremental runs or dependency
103tracking.
104
105Another challenge is configuration. Mypy and Pylint support using configuration
106files to select which checks to run and how to apply them. Both tools only
107support using a single configuration file for an entire run, which poses a
108challenge to modular middleware systems where different parts of a project may
109require different configurations.
110
111Protocol buffers
112----------------
113`Protocol buffers <https://developers.google.com/protocol-buffers>`_ are an
114efficient system for serializing structured data. They are widely used by Google
115and other companies.
116
117The protobuf compiler ``protoc`` generates Python modules from ``.proto`` files.
118``protoc`` strictly generates protobuf modules according to their directory
119structure. This works well in a monorepo, but poses a challenge to a middleware
120system like Pigweed. Generating protobufs by path also makes integrating
121protobufs with existing packages awkward.
122
123Requirements
124============
125Pigweed aims to provide high quality software components and a fast, effective,
126flexible development experience for its customers. Pigweed's high-level goals
127and the `challenges`_ described above inform these requirements for the Pigweed
128Python build.
129
130- Integrate seamlessly with the other Pigweed build tools.
131- Easy to use independently, even if primarily using a different build system.
132- Support standard packaging and distribution with setuptools, wheel, and pip.
133- Correctly manage interdependent local Python packages.
134- Out-of-the-box support for writing and running tests.
135- Preconfigured, trivial-to-run static analysis integration for Pylint and Mypy.
136- Fast, dependency-aware incremental rebuilds and test execution, suitable for
137  use with :ref:`module-pw_watch`.
138- Seamless protocol buffer support.
139
140Detailed design
141===============
142
143Build automation tool
144---------------------
145Existing Python tools may be effective for Python codebases, but their utility
146is more limited in a multi-language project like Pigweed. The cost of bringing
147up and maintaining an additional build automation system for a single language
148is high.
149
150Pigweed uses GN as its primary build system for all languages. While GN does not
151natively support Python, adding support is straightforward with GN templates.
152
153GN has strong multi-toolchain and multi-language capabilities. In GN, it is
154straightforward to share targets and artifacts between different languages. For
155example, C++, Go, and Python targets can depend on the same protobuf
156declaration. When using GN for multiple languages, Ninja schedules build steps
157for all languages together, resulting in faster total build times.
158
159Not all Pigweed users build with GN. Of Pigweed's three supported build systems,
160GN is the fastest, lightest weight, and easiest to run. It also has simple,
161clean syntax. This makes it feasible to use GN only for Python while building
162primarily with a different system.
163
164Given these considerations, GN is an ideal choice for Pigweed's Python build.
165
166.. _docs-python-build-structure:
167
168Module structure
169----------------
170Pigweed Python code is structured into standard Python packages. This makes it
171simple to package and distribute Pigweed Python packages with common Python
172tools.
173
174Like all Pigweed source code, Python packages are organized into Pigweed
175modules. A module's Python package is nested under a ``py/`` directory (see
176:ref:`docs-module-structure`).
177
178.. code-block::
179  :caption: Example layout of a Pigweed Python package.
180  :name: python-file-tree
181
182  module_name/
183  ├── py/
184  │   ├── BUILD.gn
185  │   ├── setup.cfg
186  │   ├── setup.py
187  │   ├── pyproject.toml
188  │   ├── package_name/
189  │   │   ├── module_a.py
190  │   │   ├── module_b.py
191  │   │   ├── py.typed
192  │   │   └── nested_package/
193  │   │       ├── py.typed
194  │   │       └── module_c.py
195  │   ├── module_a_test.py
196  │   └── module_c_test.py
197  └── ...
198
199The ``BUILD.gn`` declares this package in GN. For upstream Pigweed, a presubmit
200check in ensures that all Python files are listed in a ``BUILD.gn``.
201
202Pigweed prefers to define Python packages using ``setup.cfg`` files. In the
203above file tree ``setup.py`` and ``pyproject.toml`` files are stubs with the
204following content:
205
206.. code-block::
207  :caption: setup.py
208  :name: setup-py-stub
209
210  import setuptools  # type: ignore
211  setuptools.setup()  # Package definition in setup.cfg
212
213.. code-block::
214  :caption: pyproject.toml
215  :name: pyproject-toml-stub
216
217  [build-system]
218  requires = ['setuptools', 'wheel']
219  build-backend = 'setuptools.build_meta'
220
221The stub ``setup.py`` file is there to support running ``pip install --editable``.
222
223Each ``pyproject.toml`` file is required to specify which build system should be
224used for the given Python package. In Pigweed's case it always specifies using
225setuptools.
226
227.. seealso::
228
229   - ``setup.cfg`` examples at `Configuring setup() using setup.cfg files`_
230   - ``pyproject.toml`` background at `Build System Support - How to use it?`_
231
232
233.. _module-pw_build-python-target:
234
235pw_python_package targets
236-------------------------
237The key abstraction in the Python build is the ``pw_python_package``.
238A ``pw_python_package`` represents a Python package as a GN target. It is
239implemented with a GN template. The ``pw_python_package`` template is documented
240in :ref:`module-pw_build-python`.
241
242The key attributes of a ``pw_python_package`` are
243
244- a ``setup.py`` file,
245- source files,
246- test files,
247- dependencies on other ``pw_python_package`` targets.
248
249A ``pw_python_package`` target is composed of several GN subtargets. Each
250subtarget represents different functionality in the Python build.
251
252- ``<name>`` - Represents the Python files in the build, but does not take any
253  actions. All subtargets depend on this target.
254- ``<name>.tests`` - Runs all tests for this package.
255
256  - ``<name>.tests.<test_file>`` - Runs the specified test.
257
258- ``<name>.lint`` - Runs static analysis tools on the Python code. This is a
259  group of two subtargets:
260
261  - ``<name>.lint.mypy`` - Runs Mypy on all Python files, if enabled.
262  - ``<name>.lint.pylint`` - Runs Pylint on all Python files, if enabled.
263
264- ``<name>.install`` - Installs the package in a Python virtual environment.
265- ``<name>.wheel`` - Builds a Python wheel for this package.
266
267To avoid unnecessary duplication, all Python actions are executed in the default
268toolchain, even if they are referred to from other toolchains.
269
270Testing
271^^^^^^^
272Tests for a Python package are listed in its ``pw_python_package`` target.
273Adding a new test is simple: write the test file and list it in its accompanying
274Python package. The build will run the it when the test, the package, or one
275of its dependencies is updated.
276
277Static analysis
278^^^^^^^^^^^^^^^
279``pw_python_package`` targets are preconfigured to run Pylint and Mypy on their
280source and test files. Users may specify which  ``pylintrc`` and ``mypy.ini``
281files to
282use on a per-package basis. The configuration files may also be provided in the
283directory structure; the tools will locate them using their standard means. Like
284tests, static analysis is only run when files or their dependencies change.
285
286Packages may opt out of static analysis as necessary.
287
288Installing packages in a virtual environment
289^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
290Python packages declared in the Python build may be installed in a specified
291`virtual environment <https://docs.python.org/3/tutorial/venv.html>`_. The
292default venv to use may be specified using a GN build arg. The venv may be
293overridden for individual targets. The Python build tracks installation status
294of packages based on which venv is in use.
295
296The Python build examines the ``VIRTUAL_ENV`` environment variable to determine
297the current venv. If the selected virtual environment is active, packages are
298installed directly into it. If the venv is not active, it is activated before
299installing the packages.
300
301.. admonition:: Under construction
302
303  Pigweed Python targets are not yet aware of the virtual environment.
304  Currently, all actions occur in the active venv without consulting
305  ``VIRTUAL_ENV``.
306
307Python packages defined entirely in tree are installed with the ``--editable``
308option. Partially or fully generated packages are installed without that option.
309
310Building Python wheels
311^^^^^^^^^^^^^^^^^^^^^^
312Wheels are the standard format for distributing Python packages. The Pigweed
313Python build supports creating wheels for individual packages and groups of
314packages. Building the ``.wheel`` subtarget creates a ``.whl`` file for the
315package using the PyPA's `build <https://pypa-build.readthedocs.io/en/stable/>`_
316tool.
317
318The ``.wheel`` subtarget of ``pw_python_package`` records the location of
319the generated wheel with `GN metadata
320<https://gn.googlesource.com/gn/+/HEAD/docs/reference.md#var_metadata>`_.
321Wheels for a Python package and its transitive dependencies can be collected
322from the ``pw_python_package_wheels`` key. See
323:ref:`module-pw_build-python-dist`.
324
325Protocol buffers
326^^^^^^^^^^^^^^^^
327The Pigweed GN build supports protocol buffers with the ``pw_proto_library``
328target (see :ref:`module-pw_protobuf_compiler`). Python protobuf modules are
329generated as standalone Python packages by default. Protocol buffers may also be
330nested within existing Python packages. In this case, the Python package in the
331source tree is incomplete; the final Python package, including protobufs, is
332generated in the output directory.
333
334Generating setup.py
335-------------------
336The ``pw_python_package`` target in the ``BUILD.gn`` duplicates much of the
337information in the ``setup.py`` or ``setup.cfg`` file. In many cases, it would
338be possible to generate a ``setup.py`` file rather than including it in the
339source tree. However, removing the ``setup.py`` would preclude using a direct,
340editable installation from the source tree.
341
342Pigweed packages containing protobufs are generated in full or in part. These
343packages may use generated setup files, since they are always be packaged or
344installed from the build output directory.
345
346See also
347========
348
349  - :ref:`module-pw_build-python`
350  - :ref:`module-pw_build`
351  - :ref:`docs-build-system`
352
353.. _Configuring setup() using setup.cfg files: https://ipython.readthedocs.io/en/stable/interactive/reference.html#embedding
354.. _Build System Support - How to use it?: https://setuptools.readthedocs.io/en/latest/build_meta.html?highlight=pyproject.toml#how-to-use-it
355