为什么 `joblib.delayed` 不能用作装饰器?
Why does `joblib.delayed` not work as decorator?
包 joblib
有一个函数 delayed
,它捕获传递给函数的参数。它可以像这样使用:
from joblib import delayed
def f(n):
return n**2
delayed(f)(2)
# (<function f at 0x7f939eb3fe60>, (2,), {})
h = delayed(f)
h(2)
# (<function f at 0x7f939eb3fe60>, (2,), {})
后一种用法让我觉得这可以像任何其他装饰器一样使用。这是由其 documentation:
支持的
joblib.delayed(function, check_pickle=True)
Decorator used to capture the arguments of a function.
然而,这失败了:
from joblib import delayed
@delayed
def g(n):
return n**2
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "/usr/lib/python2.7/dist-packages/joblib/parallel.py", line 158, in delayed
# pickle.dumps(function)
# File "/usr/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
# raise TypeError, "can't pickle %s objects" % base.__name__
#TypeError: can't pickle function objects
我用 Python 2.7.12
试过了
看起来是命名空间问题,导致 joblib.delayed
尝试 pickle 输出函数(而不是原始函数)。
我没有研究过 joblib 代码,但你提出的方法是:
import joblib
def _func(*args, **kwargs):
'your code here'
func = joblib.delayed(_func)
虽然不理想,但很管用。
包 joblib
有一个函数 delayed
,它捕获传递给函数的参数。它可以像这样使用:
from joblib import delayed
def f(n):
return n**2
delayed(f)(2)
# (<function f at 0x7f939eb3fe60>, (2,), {})
h = delayed(f)
h(2)
# (<function f at 0x7f939eb3fe60>, (2,), {})
后一种用法让我觉得这可以像任何其他装饰器一样使用。这是由其 documentation:
支持的joblib.delayed(function, check_pickle=True)
Decorator used to capture the arguments of a function.
然而,这失败了:
from joblib import delayed
@delayed
def g(n):
return n**2
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "/usr/lib/python2.7/dist-packages/joblib/parallel.py", line 158, in delayed
# pickle.dumps(function)
# File "/usr/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
# raise TypeError, "can't pickle %s objects" % base.__name__
#TypeError: can't pickle function objects
我用 Python 2.7.12
看起来是命名空间问题,导致 joblib.delayed
尝试 pickle 输出函数(而不是原始函数)。
我没有研究过 joblib 代码,但你提出的方法是:
import joblib
def _func(*args, **kwargs):
'your code here'
func = joblib.delayed(_func)
虽然不理想,但很管用。