gpt4 book ai didi

python - 如何构建符合 PEP 517 的 C 扩展,即使用 pyproject.toml 而不是 setup.py?

转载 作者:行者123 更新时间:2023-12-04 13:53:55 28 4
gpt4 key购买 nike

我想为 CPython 构建一个 C 扩展。传统上我可以用 setup.py 做到这一点文件。但是,由于 PEP 517 中提到的原因,我更喜欢使用 pyproject.toml 的声明性方法。 .我明白 setuptools是唯一可以在所有相关平台上构建 C 扩展的构建后端。事实上,除了过时的 distutils 之外,我根本不知道有任何后端能够构建 C 扩展。 .
在此背景下,一个共同的setup.py看起来像这样:

from setuptools import setup, Extension
kwargs = dict(
name='mypackage',
# more metadata
ext_modules=[
Extension('mypackage.mymodule', ['lib/mymodule.c',
'lib/mypackage.c',
'lib/myalloc.c'],
include_dirs=['lib'],
py_limited_api=True)])

setup(**kwargs)
现在,挑战是将上述内容放入 pyproject.toml加一个 setup.cfg . setuptools文档建议使用 pyproject.toml像这样:
[build-system]
requires = [
"setuptools >=52.0",
'wheel >= 0.36']
build-backend = "setuptools.build_meta"

  • https://setuptools.readthedocs.io/en/latest/build_meta.html
  • https://setuptools.readthedocs.io/en/latest/userguide/declarative_config.html#declarative-config

  • 此外,实际的元数据应该进入 setup.cfg .但是,我还没有找到关于如何翻译 ext_modules 的任何解释。 kwarg,尤其是 Extension()调用,进入 setup.cfg句法。

    最佳答案

    pyproject.toml严格来说并不意味着要替换 setup.py ,而是在仍然需要时确保其正确执行(参见 PEP 517my answer here ):

    Where the build-backend key exists, this takes precedence and the source tree follows the format and conventions of the specified backend (as such no setup.py is needed unless the backend requires it). Projects may still wish to include a setup.py for compatibility with tools that do not use this spec.


    虽然 setuptools尝试将所有内容从脚本移动到配置文件中, it's not always possible :

    There are two types of metadata: static and dynamic.

    • Static metadata (setup.cfg): guaranteed to be the same every time. This is simpler, easier to read, and avoids many common errors, like encoding errors.
    • Dynamic metadata (setup.py): possibly non-deterministic. Any items that are dynamic or determined at install-time, as well as extension modules or extensions to setuptools, need to go into setup.py.

    Static metadata should be preferred and dynamic metadata should be used only as an escape hatch when absolutely necessary.


    事实上, setup.cfg -only projects现在只有 2 年和 setuptools will use an imaginary setup.py if it doesn't exist反正。

    话虽如此,如果您想尽可能地坚持静态方式,您可以将所有可以移动到 setup.cfg 中。归档并将其余部分留在 setup.py :
    setup.cfg
    [metadata]
    name = mypackage
    ; more metadata
    setup.py
    from setuptools import setup, Extension

    setup_args = dict(
    ext_modules = [
    Extension(
    'mypackage.mymodule',
    ['lib/mymodule.c', 'lib/mypackage.c', 'lib/myalloc.c'],
    include_dirs = ['lib'],
    py_limited_api = True
    )
    ]
    )
    setup(**setup_args)
    但我会把所有东西都放进 setup.py .

    关于python - 如何构建符合 PEP 517 的 C 扩展,即使用 pyproject.toml 而不是 setup.py?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66157987/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com