Cython 不适用于带参数的双装饰器。有解决方法吗?
Cython does not work with double decorators with argument. Is there a workaround?
我在 cythonizing 我的 python 代码时遇到问题。我试图重现我遇到的最简单的错误案例。
这里是我想要 cythonize 的代码的插图:
def some_decorator_with_arg(arg):
def decorator(func):
def wrapper(x):
return func(x) + arg
return wrapper
return decorator
class some_class():
def __init__(self):
pass
@staticmethod
@some_decorator_with_arg(1)
def some_method(a):
return a
print(some_class().some_method(1))
这在纯 python 中没有问题。但是当我用 cythonize 这段代码时,它会在 运行 时间抛出一个错误:
print(some_class().some_method(1))
TypeError: wrapper() takes exactly one argument (2 given)
编译运行没有问题。如果我写 @some_decorator_with_arg(arg=1)
我会得到另一个错误:
@some_decorator_with_arg(arg=1)
TypeError: some_decorator_with_arg() takes no keyword arguments
有人知道这个问题的解决方法吗?
我找到了最简单的解决方法——将两个(或多个)装饰器的功能合二为一,那么cython就没有问题了。例如,对于上述情况,我将执行以下操作:
def some_decorator_with_arg(arg):
def decorator(func):
def wrapper(x):
return func(x) + arg
return wrapper
return decorator
#combine the created decorator with the staticmethod functionality
def staticmethod_combined(*args,**kwargs):
return lambda func: staticmethod(some_decorator_with_arg(*args,**kwargs)(func))
class some_class():
def __init__(self):
pass
@staticmethod_combined(1)
def some_method(a):
return a
print(some_class().some_method(1))
关键字参数的问题可以通过在cythonizing时提供标志来解决always_allow_keywords=True
我在 cythonizing 我的 python 代码时遇到问题。我试图重现我遇到的最简单的错误案例。
这里是我想要 cythonize 的代码的插图:
def some_decorator_with_arg(arg):
def decorator(func):
def wrapper(x):
return func(x) + arg
return wrapper
return decorator
class some_class():
def __init__(self):
pass
@staticmethod
@some_decorator_with_arg(1)
def some_method(a):
return a
print(some_class().some_method(1))
这在纯 python 中没有问题。但是当我用 cythonize 这段代码时,它会在 运行 时间抛出一个错误:
print(some_class().some_method(1))
TypeError: wrapper() takes exactly one argument (2 given)
编译运行没有问题。如果我写 @some_decorator_with_arg(arg=1)
我会得到另一个错误:
@some_decorator_with_arg(arg=1)
TypeError: some_decorator_with_arg() takes no keyword arguments
有人知道这个问题的解决方法吗?
我找到了最简单的解决方法——将两个(或多个)装饰器的功能合二为一,那么cython就没有问题了。例如,对于上述情况,我将执行以下操作:
def some_decorator_with_arg(arg):
def decorator(func):
def wrapper(x):
return func(x) + arg
return wrapper
return decorator
#combine the created decorator with the staticmethod functionality
def staticmethod_combined(*args,**kwargs):
return lambda func: staticmethod(some_decorator_with_arg(*args,**kwargs)(func))
class some_class():
def __init__(self):
pass
@staticmethod_combined(1)
def some_method(a):
return a
print(some_class().some_method(1))
关键字参数的问题可以通过在cythonizing时提供标志来解决always_allow_keywords=True