【问题标题】:Cythonized function with a single positional argument is not possible to call using argument name无法使用参数名称调用具有单个位置参数的 Cythonized 函数
【发布时间】:2021-07-14 14:39:19
【问题描述】:

长话短说,我想对我的 python 代码进行 cythonize 并构建 .so 文件以对客户隐藏它。 采用这个简单的函数:

def one_positional_argument(a):
    print(a)

还有我的 setup.py 构建 .so 文件

from setuptools import setup, find_packages
from Cython.Build import cythonize

setup(
    name='tmp',
    version='1.0.0',
    packages=find_packages(),
    nthreads=3,
    ext_modules=cythonize(
        ["a.py"],
        compiler_directives={'language_level': 3},
        build_dir="output",
    ),
)

当我导入 .so 文件并尝试执行我的函数时,会发生以下情况:

one_positional_argument(1) # this prints 1 and works fine
one_positional_argument(a=1) # throws TypeError: one_positional_argument() takes no keyword arguments

有多种解决方法,但我想知道我是否做错了什么

附加信息: 如果我有一个带有 2 个位置参数的函数,或者一个带有默认值的位置参数,那么一切正常。该问题仅存在于 1 个位置参数。

【问题讨论】:

  • 你是如何得到 cython 的? PS我没有答案
  • 我是用pip安装的:pip install Cython
  • 顺便说一句,DavidW给出的答案如下,它有效。

标签: python python-3.x cython cythonize


【解决方案1】:

您需要 always_allow_keywords 编译器指令 (https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html#compiler-directives)。

默认情况下不允许它们是故意的兼容性/速度权衡。但是,在即将发布的 Cython v3(现在可以使用 alpha 版本...)中,这将发生变化:https://github.com/cython/cython/issues/3090

【讨论】:

  • 非常感谢。有效。我不能早点感谢你,因为我没有足够的声誉:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多