Especificação do pyproject.toml¶
Aviso
This is a technical, formal specification. For a gentle,
user-friendly guide to pyproject.toml, see
Escrevendo seu pyproject.toml.
The pyproject.toml file acts as a configuration file for packaging-related
tools (as well as other tools).
The pyproject.toml file is written in TOML. Three
tables are currently specified, namely
[build-system],
[project] and
[tool]. Other tables are reserved for future
use (tool-specific configuration should use the [tool] table).
Declaring build system dependencies: the [build-system] table¶
The [build-system] table declares any Python level dependencies that
must be installed in order to run the project’s build system
successfully.
A tabela [build-system] é usada para armazenar dados relacionados a construção. Inicialmente, apenas uma chave da tabela é válida e é obrigatória para a tabela: requires. Esta chave deve ter um valor de uma lista de strings que representam dependências necessárias para executar o sistema de construção. As strings nesta lista seguem a especificação de especificadores de versão.
An example [build-system] table for a project built with
setuptools is:
[build-system]
# Minimum requirements for the build system to execute.
requires = ["setuptools"]
Build tools are expected to use the example configuration file above as
their default semantics when a pyproject.toml file is not present.
Tools should not require the existence of the [build-system] table.
A pyproject.toml file may be used to store configuration details
other than build-related data and thus lack a [build-system] table
legitimately. If the file exists but is lacking the [build-system]
table then the default values as specified above should be used.
If the table is specified but is missing required fields then the tool
should consider it an error.
Tools may choose to present an error to the user if the file exists,
[build-system] table is missing, and there is no clear indication
that the project should be built (e.g., no setup.py/setup.cfg or other
build configuration files, and no [project] table).
To provide a type-specific representation of the resulting data from the TOML file for illustrative purposes only, the following JSON Schema would match the data format:
{
"$schema": "http://json-schema.org/schema#",
"type": "object",
"additionalProperties": false,
"properties": {
"build-system": {
"type": "object",
"additionalProperties": false,
"properties": {
"requires": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": ["requires"]
},
"tool": {
"type": "object"
}
}
}
Declaring project metadata: the [project] table¶
The [project] table specifies the project’s core metadata.
Existem dois tipos de metadados: estáticos e dinâmicos. Metadados estáticos são especificados diretamente no arquivo pyproject.toml e não podem ser especificados ou alterados por uma ferramenta (isso inclui dados referenciados pelo metadados, por exemplo, o conteúdo de arquivos referenciados pelos metadados). Os metadados dinâmicos são listados por meio da chave dynamic (definido posteriormente nesta especificação) e representam os metadados que uma ferramenta fornecerá posteriormente.
The lack of a [project] table implicitly means the build backend
will dynamically provide all keys.
As únicas chaves que precisam ser definidos estaticamente são:
name
As chaves que são obrigatórias, mas podem ser especificadas estaticamente ou listadas como dinâmicas são:
version
Todas as outras chaves são consideradas opcionais e podem ser especificadas estaticamente, listadas como dinâmicas ou não especificadas.
A lista completa de chaves permitidas na tabela [project] são:
authorsclassifiersdependenciesdescriptiondynamicentry-pointsgui-scriptsimport-namesimport-namespaceskeywordslicenselicense-filesmaintainersnameoptional-dependenciesreadmerequires-pythonscriptsurlsversion
name¶
Tipo TOML: string
Campo correspondente dos metadados principais: Name
O nome do projeto.
As ferramentas DEVEM normalizar este nome, conforme especificado por PEP 503, assim que for lido para consistência interna.
version¶
Tipo TOML: string
Campo correspondente dos metadados principais: Version
A versão do projeto, conforme definido na especificação de especificadores de versão.
Os usuários DEVEM preferir especificar versões já normalizadas.
description¶
Tipo TOML: string
Campo correspondente dos metadados principais: Summary
The summary description of the project in one line. Tools MAY error if this includes multiple lines.
readme¶
Tipo TOML: string ou tabela
Campos correspondente dos metadados principais: Description e Description-Content-Type
A descrição completa do projeto (isto é, o README).
A chave aceita uma string ou uma tabela. Se for uma string, então é um caminho relativo ao pyproject.toml para um arquivo texto contendo a descrição completa. As ferramentas DEVEM presumir que a codificação do arquivo é UTF-8. Se o caminho do arquivo termina com um sufixo .md, ou sua versão em caixa alta, então as ferramentas DEVEM presumir que o tipo de conteúdo é text/markdown. Se o caminho do arquivo termina em .rst, então as ferramentas DEVEM presumir que o tipo de conteúdo é text/x-rst. Se uma ferramenta reconhece mais extensões do que esta PEP, elas podem inferir o tipo de conteúdo para o usuário sem especificar esta chave como dynamic. Para todos os sufixos não reconhecidos quando um tipo de conteúdo não é fornecido, as ferramentas DEVEM levantar um erro.
A chave readme também pode receber uma tabela. A chave file tem um valor string que representa um caminho relativo a pyproject.toml para um arquivo contendo a descrição completa. A chave text tem um valor de string que é a descrição completa. Essas chaves são mutuamente exclusivas, portanto, as ferramentas DEVEM levantar um erro se os metadados especificarem ambas as chaves.
Uma tabela especificada na chave readme também possui uma chave content-type que recebe uma string especificando o tipo de conteúdo da descrição completa. Uma ferramenta DEVE levantar um erro se os metadados não especificarem esse campo na tabela. Se os metadados não especificarem o parâmetro charset, será considerado UTF-8. As ferramentas PODEM oferecer suporte a outras codificações, se assim o desejarem. As ferramentas PODEM oferecer suporte a tipos de conteúdo alternativos que podem transformar em um tipo de conteúdo conforme suportado pelos metadados principais. Caso contrário, as ferramentas DEVEM levantar um erro para tipos de conteúdo não suportados.
requires-python¶
Tipo TOML: string
Campo correspondente dos metadados principais: Requires-Python
Os requisitos de versão do Python do projeto.
license¶
Tipo TOML: string
Corresponding core metadata field: License-Expression
Text string that is a valid SPDX license expression, as specified in Expressão de licença. Tools SHOULD validate and perform case normalization of the expression.
This key should only be specified if the license expression for any
and all distribution files created by a build backend using the
pyproject.toml is the same as the one specified. If the license
expression will differ then it should either be specified as dynamic or
not set at all.
Legacy specification¶
Tipo TOML: tabela
Corresponding core metadata field: License
The table may have one of two keys. The file key has a string
value that is a file path relative to pyproject.toml to the file
which contains the license for the project. Tools MUST assume the
file’s encoding is UTF-8. The text key has a string value which is
the license of the project. These keys are mutually exclusive, so a
tool MUST raise an error if the metadata specifies both keys.
The table subkeys were deprecated by PEP 639 in favor of the string value.
license-files¶
Tipo TOML: vetor de strings
Corresponding core metadata field: License-File
An array specifying paths in the project source tree relative to the project
root directory (i.e. directory containing pyproject.toml or legacy project
configuration files, e.g. setup.py, setup.cfg, etc.)
to file(s) containing licenses and other legal notices to be
distributed with the package.
The strings MUST contain valid glob patterns, as specified in glob patterns.
Patterns are relative to the directory containing pyproject.toml,
Tools MUST assume that license file content is valid UTF-8 encoded text, and SHOULD validate this and raise an error if it is not.
Build tools:
MUST include all files matched by a listed pattern in all distribution archives.
MUST list each matched file path under a License-File field in the Core Metadata.
If the license-files key is present and
is set to a value of an empty array, then tools MUST NOT include any
license files and MUST NOT raise an error.
If the license-files key is not defined, tools can decide how to handle
license files. For example they can choose not to include any files or use
their own logic to discover the appropriate files in the distribution.
keywords¶
Tipo TOML: vetor de strings
Campo correspondente dos metadados principais: Keywords
As palavras-chave do projeto.
classifiers¶
Tipo TOML: vetor de strings
Campo correspondente dos metadados principais: Classifier
Classificadores Trove que se aplicam ao projeto.
The use of License :: classifiers is deprecated and tools MAY issue a
warning informing users about that.
Build tools MAY raise an error if both the license string value
(translating to License-Expression metadata field) and the License ::
classifiers are used.
urls¶
Tipo TOML: tabela com chaves e valores de strings
Campo correspondente dos metadados principais: Project-URL
A table of URLs where the key is the URL label and the value is the URL itself. See Well-known Project URLs in Metadata for normalization rules and well-known rules when processing metadata for presentation.
Pontos de entrada¶
Tipo TOML: tabela (
[project.scripts],[project.gui-scripts]e[project.entry-points])
Existem três tabelas relacionadas aos pontos de entrada. A tabela [project.scripts] corresponde ao grupo console_scripts na especificação de pontos de entrada. A chave da tabela é o nome do ponto de entrada e o valor é a referência do objeto.
A tabela [project.gui-scripts] corresponde ao grupo gui_scripts na especificação de pontos de entrada. Seu formato é o mesmo que [project.scripts].
A tabela [project.entry-points] é uma coleção de tabelas. O nome de cada subtabela é um grupo de pontos de entrada. A chave e a semântica do valor são iguais a [project.scripts]. Os usuários NÃO DEVEM criar subtabelas aninhadas, mas sim manter os grupos de pontos de entrada em apenas um nível de profundidade.
Backends de construção DEVEM levantar um erro se os metadados definem uma tabela [project.entry-points.console_scripts] ou [project.entry-points.gui_scripts], pois elas seriam ambíguas perante [project.scripts] e [project.gui-scripts], respectivamente.
dependencies¶
TOML type: Array of dependency specifier strings (
dependencies)Corresponding core metadata field: Requires-Dist
dependencies lists the expected dependencies of the project as an
array of strings.
Each string represents a dependency of the project and MUST be formatted as a valid dependency specifier.
Each string maps directly to a Requires-Dist entry.
Dependencies listed in this array are always considered for installation, but may still contain environment markers that cause them to be skipped in some environments.
optional-dependencies¶
TOML type: table with string keys mapping to arrays of dependency specifier strings (
optional-dependencies)Corresponding core metadata fields: Requires-Dist and Provides-Extra
optional-dependencies is a table where each key specifies
an extra and whose value is an array of strings using the same format as the
dependencies array (the strings in the
arrays must be valid dependency specifiers).
The keys MUST be valid values for Provides-Extra. Each value in the array thus becomes a corresponding Requires-Dist entry for the matching Provides-Extra metadata.
The optionality of these dependencies is recorded by modifying the environment
marker clause on the related Requires-Dist entries to check the extra name.
Optional dependencies are thus only considered for installation if installation
if the associated extra name is requested.
import-names¶
Tipo TOML: vetor de strings
Corresponding core metadata field: Import-Name
An array of strings specifying the import names that the project exclusively
provides when installed. Each string MUST be a valid Python identifier or can
be empty. An import name MAY be followed by a semicolon and the term “private”
(e.g. "; private") with any amount of whitespace surrounding the semicolon.
Projects SHOULD list all the shortest import names that are exclusively provided
by the project. If any of the shortest names are dotted names, all intervening
names from that name to the top-level name should also be listed appropriately
in import-names and/or import-namespaces. For instance, a project which
is a single package named spam with multiple submodules would only list
project.import-names = ["spam"]. A project that lists spam.bacon.eggs
would also need to account for spam and spam.bacon appropriately in
import-names and import-namespaces. Listing all names acts as a check
that the intent of the import names is as expected. As well, projects SHOULD
list all import names, public or private, using the ; private modifier as
appropriate.
If a project lists the same name in both import-names and
import-namespaces, then tools MUST raise an error due to ambiguity.
Projects MAY set import-names to an empty array to represent a project with
no import names (i.e. there are no Python modules of any kind in the
distribution file).
Build back-ends MAY support dynamically calculating the value if the user
declares the key in project.dynamic.
Exemplos:
[project]
name = "pillow"
import-names = ["PIL"]
[project]
name = "myproject"
import-names = ["mypackage", "_private_module ; private"]
import-namespaces¶
Tipo TOML: vetor de strings
Corresponding core metadata field: Import-Namespace
An array of strings specifying the import names that the project provides when
installed, but not exclusively. Each string MUST be a valid Python identifier.
An import name MAY be followed by a semicolon and the term “private” (e.g.
"; private") with any amount of whitespace surrounding the semicolon. Note
that unlike import-names, import-namespaces CANNOT be an empty array.
Projects SHOULD list all the shortest import names that are exclusively provided
by the project. If any of the shortest names are dotted names, all intervening
names from that name to the top-level name should also be listed appropriately
in import-names and/or import-namespaces.
This field is used for namespace packages where multiple projects can contribute
to the same import namespace. Projects all listing the same import name in
import-namespaces can be installed together without shadowing each other.
If a project lists the same name in both import-names and
import-namespaces, then tools MUST raise an error due to ambiguity.
Build back-ends MAY support dynamically calculating the value if the user
declares the key in project.dynamic.
Example:
[project]
name = "zope-interface"
import-namespaces = ["zope"]
import-names = ["zope.interface"]
dynamic¶
Tipo TOML: vetor de string
Campo correspondente dos metadados principais: Dynamic
Especifica quais chaves listadas por esta PEP foram intencionalmente não especificadas para que outra ferramenta possa/vai fornecer tais metadados dinamicamente. Isso delineia claramente quais metadados são propositalmente não especificados e espera-se que permaneçam não especificados em comparação a serem fornecidos por meio de ferramentas posteriormente.
Um backend de construção DEVE respeitar metadados especificados estaticamente (o que significa que os metadados não listam a chave em
dynamic).Um backend de construção DEVE gerar um erro se os metadados especificarem
nameemdynamic.Se a especificação de metadados principais lista um campo como “Required”, então os metadados DEVEM especificar a chave estaticamente ou listá-la em
dynamic(backends de construção DEVEM gerar um erro, caso contrário , ou seja, não deve ser possível que uma chave obrigatória não seja listada de alguma forma na tabela[project]).Se a especificação de metadados principais listar um campo como “Optional”, os metadados PODEM listá-lo em
dynamicse a expectativa for um backend de construção fornecerá os dados para a chave mais tarde.Os backends de construção DEVEM levantar um erro se os metadados especificarem uma chave estaticamente, além de serem listados em
dynamic.Se os metadados não listam uma chave em
dynamic, então um backend de construção NÃO PODE preencher os metadados necessários em nome do usuário (ou seja,dynamicé a única maneira de permitir que uma ferramenta preencha metadados e o usuário deve optar pelo preenchimento).Os backends de construção DEVEM levantar um erro se os metadados especificarem uma chave em
dynamic, mas o backend de construção não foi capaz de determinar os dados para ele (omitir os dados, se determinado como o valor exato, é aceitável) .
Arbitrary tool configuration: the [tool] table¶
The [tool] table is where any tool related to your Python
project, not just build tools, can have users specify configuration
data as long as they use a sub-table within [tool], e.g. the
flit tool would store its
configuration in [tool.flit].
A mechanism is needed to allocate names within the tool.*
namespace, to make sure that different projects do not attempt to use
the same sub-table and collide. Our rule is that a project can use
the subtable tool.$NAME if, and only if, they own the entry for
$NAME in the Cheeseshop/PyPI.
Histórico¶
May 2016: The initial specification of the
pyproject.tomlfile, with just a[build-system]containing arequireskey and a[tool]table, was approved through PEP 518.November 2020: The specification of the
[project]table was approved through PEP 621.December 2024: The
licensekey was redefined, thelicense-fileskey was added andLicense::classifiers were deprecated through PEP 639.September 2025: Clarity that the
licensekey applies to all distribution files generated from thepyproject.tomlfile.October 2025: The
import-namesandimport-namespaceskeys were added through PEP 794.January 2026: Replaced outdated direct reference to PEP 508 with a reference to Especificadores de dependência.