【Py】由单个参数导致的Cython编译报错:takes no keyword arguments

本文介绍了一个关于Cython编译时出现的奇怪错误,当尝试使用关键字参数传递字典时,从.py文件转换到.so文件会导致TypeError。文章详细解释了问题的原因,并提供了设置compiler_directives参数来解决该问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在写接口的时候发现一个非常诡异的问题:
下面的代码在以.py文件执行时没有问题

# test.py
def foo(bar):
    print(bar)

bar = {'bar':123}

foo(**bar)

一旦将其编译为.so文件,再执行就会报错

def foo(bar):
Type 'copyright', 'credits' or 'license' for more information
IPython 7.24.1 -- An enhanced Interactive Python. Type '?' for help.

from distutils.core import setup
In [1]: import param_test
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-be0f14611aca> in <module>
----> 1 import param_test

~/Git/test/cython_test/param_test.cpython-38-darwin.so in init param_test()

TypeError: foo() takes no keyword arguments

查了一下原来是因为参数个数为0和1时,在进行编译的时候会自动禁用关键字参数,所以导致报错说这个函数没有关键字参数。

官方文档的解释是:
在这里插入图片描述
大概意思就是“一切为了性能”

解决办法就是将always_allow_keywords设置为True即可

# setup.py
...
setup(
    ext_modules=cythonize(
        './param_test.py', 
        compiler_directives={'always_allow_keywords': True}
    )
)

参考:
https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html#compiler-directives
https://github.com/cython/cython/issues/2136#issuecomment-376968421

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值