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 180 module_name/ 181 ├── py/ 182 │ ├── BUILD.gn 183 │ ├── setup.py 184 │ ├── package_name/ 185 │ │ ├── module_a.py 186 │ │ ├── module_b.py 187 │ │ ├── py.typed 188 │ │ └── nested_package/ 189 │ │ ├── py.typed 190 │ │ └── module_c.py 191 │ ├── module_a_test.py 192 │ └── module_c_test.py 193 └── ... 194 195The ``BUILD.gn`` declares this package in GN. For upstream Pigweed, a presubmit 196check in ensures that all Python files are listed in a ``BUILD.gn``. 197 198.. _module-pw_build-python-target: 199 200pw_python_package targets 201------------------------- 202The key abstraction in the Python build is the ``pw_python_package``. 203A ``pw_python_package`` represents a Python package as a GN target. It is 204implemented with a GN template. The ``pw_python_package`` template is documented 205in :ref:`module-pw_build-python`. 206 207The key attributes of a ``pw_python_package`` are 208 209- a ``setup.py`` file, 210- source files, 211- test files, 212- dependencies on other ``pw_python_package`` targets. 213 214A ``pw_python_package`` target is composed of several GN subtargets. Each 215subtarget represents different functionality in the Python build. 216 217- ``<name>`` - Represents the Python files in the build, but does not take any 218 actions. All subtargets depend on this target. 219- ``<name>.tests`` - Runs all tests for this package. 220 221 - ``<name>.tests.<test_file>`` - Runs the specified test. 222 223- ``<name>.lint`` - Runs static analysis tools on the Python code. This is a 224 group of two subtargets: 225 226 - ``<name>.lint.mypy`` - Runs Mypy on all Python files, if enabled. 227 - ``<name>.lint.pylint`` - Runs Pylint on all Python files, if enabled. 228 229- ``<name>.install`` - Installs the package in a Python virtual environment. 230- ``<name>.wheel`` - Builds a Python wheel for this package. 231 232To avoid unnecessary duplication, all Python actions are executed in the default 233toolchain, even if they are referred to from other toolchains. 234 235Testing 236^^^^^^^ 237Tests for a Python package are listed in its ``pw_python_package`` target. 238Adding a new test is simple: write the test file and list it in its accompanying 239Python package. The build will run the it when the test, the package, or one 240of its dependencies is updated. 241 242Static analysis 243^^^^^^^^^^^^^^^ 244``pw_python_package`` targets are preconfigured to run Pylint and Mypy on their 245source and test files. Users may specify which ``pylintrc`` and ``mypy.ini`` 246files to 247use on a per-package basis. The configuration files may also be provided in the 248directory structure; the tools will locate them using their standard means. Like 249tests, static analysis is only run when files or their dependencies change. 250 251Packages may opt out of static analysis as necessary. 252 253Installing packages in a virtual environment 254^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 255Python packages declared in the Python build may be installed in a specified 256`virtual environment <https://docs.python.org/3/tutorial/venv.html>`_. The 257default venv to use may be specified using a GN build arg. The venv may be 258overridden for individual targets. The Python build tracks installation status 259of packages based on which venv is in use. 260 261The Python build examines the ``VIRTUAL_ENV`` environment variable to determine 262the current venv. If the selected virtual environment is active, packages are 263installed directly into it. If the venv is not active, it is activated before 264installing the packages. 265 266.. admonition:: Under construction 267 268 Pigweed Python targets are not yet aware of the virtual environment. 269 Currently, all actions occur in the active venv without consulting 270 ``VIRTUAL_ENV``. 271 272Python packages defined entirely in tree are installed with the ``--editable`` 273option. Partially or fully generated packages are installed without that option. 274 275Building Python wheels 276^^^^^^^^^^^^^^^^^^^^^^ 277Wheels are the standard format for distributing Python packages. The Pigweed 278Python build supports creating wheels for individual packages and groups of 279packages. Building the ``.wheel`` subtarget creates a ``.whl`` file for the 280package using the PyPA's `build <https://pypa-build.readthedocs.io/en/stable/>`_ 281tool. 282 283The ``.wheel`` subtarget of ``pw_python_package`` records the location of 284the generated wheel with `GN metadata 285<https://gn.googlesource.com/gn/+/master/docs/reference.md#var_metadata>`_. 286Wheels for a Python package and its transitive dependencies can be collected 287from the ``pw_python_package_wheels`` key. See 288:ref:`module-pw_build-python-wheels`. 289 290Protocol buffers 291^^^^^^^^^^^^^^^^ 292The Pigweed GN build supports protocol buffers with the ``pw_proto_library`` 293target (see :ref:`module-pw_protobuf_compiler`). Python protobuf modules are 294generated as standalone Python packages by default. Protocol buffers may also be 295nested within existing Python packages. In this case, the Python package in the 296source tree is incomplete; the final Python package, including protobufs, is 297generated in the output directory. 298 299Generating setup.py 300------------------- 301The ``pw_python_package`` target in the ``BUILD.gn`` duplicates much of the 302information in the ``setup.py`` or ``setup.cfg`` file. In many cases, it would 303be possible to generate a ``setup.py`` file rather than including it in the 304source tree. However, removing the ``setup.py`` would preclude using a direct, 305editable installation from the source tree. 306 307Pigweed packages containing protobufs are generated in full or in part. These 308packages may use generated setup files, since they are always be packaged or 309installed from the build output directory. 310 311See also 312======== 313 314 - :ref:`module-pw_build-python` 315 - :ref:`module-pw_build` 316 - :ref:`docs-build-system` 317