Recomendações de ferramentas¶
O cenário de empacotamento do Python consiste em muitas ferramentas diferentes. Para muitas tarefas, o Python Packaging Authority (PyPA, o grupo de trabalho que engloba muitas ferramentas de empacotamento e mantém este guia) propositalmente não faz uma recomendação geral; por exemplo, a razão pela qual existem muitos backends de construção é que o cenário foi aberto para permitir o desenvolvimento de novos backends que atendam melhor às necessidades de determinados usuários do que o backend anteriormente exclusivo, setuptools. Este guia aponta algumas ferramentas que são amplamente reconhecidas e também faz algumas recomendações de ferramentas que você não deve usar porque estão descontinuadas ou são inseguras.
Ambientes virtuais¶
As ferramentas padrão para criar e usar ambientes virtuais manualmente são virtualenv (projeto PyPA) e venv (parte da biblioteca padrão Python, embora falte alguns recursos do virtualenv) .
Instalando pacotes¶
pip é a ferramenta padrão para instalar pacotes do PyPI. Você pode querer ler as recomendações do pip para obter instalações seguras. Pip está disponível por padrão na maioria das instalações do Python através do pacote de biblioteca padrão ensurepip.
Alternativamente, considere pipx para o caso de uso específico de instalação de aplicativos Python que são distribuídos por meio de PyPI e executados a partir da linha de comando. Pipx é um wrapper em torno de pip e venv que instala cada aplicativo em um ambiente virtual dedicado. Isso evita conflitos entre as dependências de diferentes aplicações, e também com aplicações de todo o sistema que utilizam o mesmo interpretador Python (especialmente no Linux).
Especificamente para software científico, considere conda ou Spack.
Por fazer
Escreva uma comparação “pip vs. Conda”, aqui ou em uma nova discussão.
Não use easy_install
(parte de Setuptools), que foi descontinuado em favor do pip (veja pip vs easy_install para detalhes). Da mesma forma, não use python setup.py install
ou python setup.py develop
, que também foram descontinuados (veja setup.py foi descontinuado? para aprofundamento e Como modernizar um projeto baseado em setup.py? para aconselhamento sobre migração).
Arquivos de bloqueio¶
pip-tools e Pipenv são duas ferramentas reconhecidas para criar arquivos de bloqueio, que contêm as versões exatas de todos os pacotes instalados em um ambiente, para fins de reprodutibilidade.
Backends de construção¶
Importante
Por favor, lembre-se: este documento não procura orientar o leitor para uma ferramenta específica, apenas enumerar ferramentas comuns. Diferentes casos de uso geralmente precisam de fluxos de trabalho especializados.
Popular build backends for pure-Python packages include, in alphabetical order:
Flit-core – developed with but separate from flit. A minimal and opinionated build backend. It does not support plugins.
Hatchling – developed with but separate from hatch. Supports plugins.
PDM-backend – developed with but separate from pdm. Supports plugins.
Poetry-core – developed with but separate from poetry. Supports plugins.
Unlike other backends on this list, Poetry-core does not support the standard [project] table (it uses a different format, in the
[tool.poetry]
table).Setuptools, which used to be the only build backend. Supports plugins.
Cuidado
If you use setuptools, please be aware that some features that predate standardisation efforts are now deprecated and only temporarily kept for compatibility.
In particular, do not use direct
python setup.py
invocations. On the other hand, configuring setuptools with asetup.py
file is still fully supported, although it is recommended to use the modern [project] table in pyproject.toml (orsetup.cfg
) whenever possible and keepsetup.py
only if programmatic configuration is needed. See setup.py foi descontinuado?.Other examples of deprecated features you should not use include the
setup_requires
argument tosetup()
(use the [build-system] table inpyproject.toml
instead), and theeasy_install
command (cf. pip vs easy_install).
Do not use distutils, which is deprecated, and has been removed from the standard library in Python 3.12, although it still remains available from setuptools.
For packages with extension modules, it is best to use a build system with dedicated support for the language the extension is written in, for example:
Setuptools – natively supports C and C++ (with third-party plugins for Go and Rust),
meson-python – C, C++, Fortran, Rust, and other languages supported by Meson,
scikit-build-core – C, C++, Fortran, and other languages supported by CMake,
Maturin – Rust, via Cargo.
Building distributions¶
The standard tool to build source distributions and wheels for uploading to PyPI is construir. It
will invoke whichever build backend you declared in pyproject.toml
.
Do not use python setup.py sdist
and python setup.py bdist_wheel
for
this task. All direct invocations of setup.py
are deprecated.
If you have extension modules and want to distribute wheels for multiple platforms, use cibuildwheel as part of your CI setup to build distributable wheels.
Uploading to PyPI¶
For projects hosted on or published via supported CI/CD platforms, it is recommended to use the Trusted Publishing, which allows the package to be securely uploaded to PyPI from a CI/CD workflow without a manually configured API token.
As of November 2024, PyPI supports the following platforms as Trusted Publishing providers:
GitHub Actions (on
https://github.com
)GitLab CI/CD (on
https://gitlab.com
)ActiveState
Google Cloud
The other available method is to upload the package manually using twine.
Perigo
Never use python setup.py upload
for this task. In addition to being
deprecated, it is insecure.
Workflow tools¶
These tools are environment managers that automatically manage virtual environments for a project. They also act as “task runners”, allowing you to define and invoke tasks such as running tests, compiling documentation, regenerating some files, etc. Some of them provide shortcuts for building distributions and uploading to PyPI, and some support lock files for applications. They often call the tools mentioned above under the hood. In alphabetical order: