Previously, when a user or a command line tool (let's call it a "frontend")
needed to make a request of setuptools to take a certain action, for
example, generating a list of installation requirements, the frontend
would call "setup.py egg_info"or"setup.py bdist_wheel" on the command line.
PEP 517 defines a different method of interfacing with setuptools. Rather
than calling "setup.py" directly, the frontend should:
1. Set the current directory to the directory with a setup.py file
2. Import this module into a safe python interpreter (one in which
setuptools can potentially set global variables or crash hard).
3. Call one of the functions defined in PEP 517.
What each function does is defined in PEP 517. However, here is a "casual"
definition of the functions (this definition should not be relied on for
bug reports or API stability):
- `build_wheel`: build a wheel in the folder andreturn the basename
- `get_requires_for_build_wheel`: get the `setup_requires` to build
- `prepare_metadata_for_build_wheel`: get the `install_requires`
- `build_sdist`: build an sdist in the folder andreturn the basename
- `get_requires_for_build_sdist`: get the `setup_requires` to build
Again, this isnot a formal definition! Just a "taste" of the module. """
from __future__ import annotations
import contextlib import io import os import shlex import shutil import sys import tempfile import tokenize import warnings from pathlib import Path from typing import TYPE_CHECKING, Dict, Iterable, Iterator, List, Union
import setuptools
from . import errors from ._path import StrPath, same_path from ._reqs import parse_strings from .warnings import SetuptoolsDeprecationWarning
import distutils from distutils.util import strtobool
if TYPE_CHECKING: from typing_extensions import TypeAlias
class SetupRequirementsError(BaseException): def __init__(self, specifiers):
self.specifiers = specifiers
class Distribution(setuptools.dist.Distribution): def fetch_build_eggs(self, specifiers):
specifier_list = list(parse_strings(specifiers))
raise SetupRequirementsError(specifier_list)
@classmethod
@contextlib.contextmanager def patch(cls): """
Replace
distutils.dist.Distribution with this class for the duration of this context. """
orig = distutils.core.Distribution
distutils.core.Distribution = cls try: yield finally:
distutils.core.Distribution = orig
Under PEP 517, the backend reports build dependencies to the frontend, and the frontend is responsible for ensuring they're installed.
So setuptools (acting as a backend) should nottry to install them. """
orig = setuptools._install_setup_requires
setuptools._install_setup_requires = lambda attrs: None try: yield finally:
setuptools._install_setup_requires = orig
def _get_immediate_subdirectories(a_dir): return [
name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name))
]
def _file_with_extension(directory: StrPath, extension: str | tuple[str, ...]):
matching = (f for f in os.listdir(directory) if f.endswith(extension)) try:
(file,) = matching except ValueError: raise ValueError( 'No distribution was found. Ensure that `setup.py` ' 'is not empty and that it calls `setup()`.'
) fromNone return file
- pip will pass both key and value as strings and overwriting repeated keys
(pypa/pip#11059).
- build will accumulate values associated with repeated keys in a list.
It will also accept keys with no associated value.
This means that an option passed by build can be ``str | list[str] | None``.
- PEP 517 specifies that ``config_settings`` is an optional dict. """
class _ConfigSettingsTranslator: """Translate ``config_settings`` into distutils-style command arguments.
Only a limited number of options is currently supported. """
# See pypa/setuptools#1928 pypa/setuptools#2491
def _get_config(self, key: str, config_settings: _ConfigSettings) -> list[str]: """
Get the value of a specific key in ``config_settings`` as a list of strings.
def _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]: """
Let the user specify ``verbose`` or ``quiet`` + escape hatch via
``--global-option``.
Note: ``-v``, ``-vv``, ``-vvv`` have similar effects in setuptools,
so we just have to cover the basic scenario ``-v``.
def __dist_info_args(self, config_settings: _ConfigSettings) -> Iterator[str]: """
The ``dist_info`` command accepts ``tag-date`` and ``tag-build``.
.. warning::
We cannot use this yet as it requires the ``sdist`` and ``bdist_wheel``
commands run in ``build_sdist`` and ``build_wheel`` to reuse the egg-info
directory created in ``prepare_metadata_for_build_wheel``.
def _arbitrary_args(self, config_settings: _ConfigSettings) -> Iterator[str]: """
Users may expect to pass arbitrary lists of arguments to a command
via "--global-option" (example provided in PEP 517 of a "escape hatch").
class _BuildMetaBackend(_ConfigSettingsTranslator): def _get_build_requires(self, config_settings, requirements):
sys.argv = [
*sys.argv[:1],
*self._global_args(config_settings), "egg_info",
] try: with Distribution.patch():
self.run_setup() except SetupRequirementsError as e:
requirements += e.specifiers
return requirements
def run_setup(self, setup_script='setup.py'): # Note that we can reuse our build directory between calls # Correctness comes first, then optimization later
__file__ = os.path.abspath(setup_script)
__name__ = '__main__'
with _open_setup_script(__file__) as f:
code = f.read().replace(r'\r\n', r'\n')
try:
exec(code, locals()) except SystemExit as e: if e.code: raise # We ignore exit code indicating success
SetuptoolsDeprecationWarning.emit( "Running `setup.py` directly as CLI tool is deprecated.", "Please avoid using `sys.exit(0)` or similar statements " "that don't fit in the paradigm of a configuration file.",
see_url="https://blog.ganssle.io/articles/2021/10/" "setup-py-deprecated.html",
)
def _bubble_up_info_directory(self, metadata_directory: str, suffix: str) -> str: """
PEP 517 requires that the .dist-info directory be placed in the
metadata_directory. To comply, we MUST copy the directory to the root.
Returns the basename of the info directory, e.g. `proj-0.0.0.dist-info`. """
info_dir = self._find_info_directory(metadata_directory, suffix) ifnot same_path(info_dir.parent, metadata_directory):
shutil.move(str(info_dir), metadata_directory) # PEP 517 allow other files and dirs to exist in metadata_directory return info_dir.name
def _find_info_directory(self, metadata_directory: str, suffix: str) -> Path: for parent, dirs, _ in os.walk(metadata_directory):
candidates = [f for f in dirs if f.endswith(suffix)]
if len(candidates) != 0 or len(dirs) != 1: assert len(candidates) == 1, f"Multiple {suffix} directories found" return Path(parent, candidates[0])
msg = f"No {suffix} directory found in {metadata_directory}" raise errors.InternalError(msg)
class _BuildMetaLegacyBackend(_BuildMetaBackend): """Compatibility backend for setuptools
This is a version of setuptools.build_meta that endeavors
to maintain backwards
compatibility with pre-PEP 517 modes of invocation. It
exists as a temporary
bridge between the old packaging mechanism and the new
packaging mechanism, and will eventually be removed. """
def run_setup(self, setup_script='setup.py'): # In order to maintain compatibility with scripts assuming that # the setup.py script is in a directory on the PYTHONPATH, inject # '' into sys.path. (pypa/setuptools#1642)
sys_path = list(sys.path) # Save the original path
script_dir = os.path.dirname(os.path.abspath(setup_script)) if script_dir notin sys.path:
sys.path.insert(0, script_dir)
# Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to # get the directory of the source code. They expect it to refer to the # setup.py script.
sys_argv_0 = sys.argv[0]
sys.argv[0] = setup_script
try:
super().run_setup(setup_script=setup_script) finally: # While PEP 517 frontends should be calling each hook in a fresh # subprocess according to the standard (and thus it should not be # strictly necessary to restore the old sys.path), we'll restore # the original path so that the path manipulation does not persist # within the hook after run_setup is called.
sys.path[:] = sys_path
sys.argv[0] = sys_argv_0
# The primary backend
_BACKEND = _BuildMetaBackend()
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.