【发布时间】:2019-12-31 12:27:38
【问题描述】:
我正在尝试创建一个简单的 joblib 函数,它将评估表达式并腌制结果,同时检查腌制文件是否存在。 但是当我将此函数放在其他文件中并在将文件的路径添加到 sys.path 后导入该函数时。我收到错误。
from pathlib import Path
import joblib as jl
def saveobj(filename, expression_obj,ignore_file = False):
fname = Path(filename)
if fname.exists() and not ignore_file:
obj = jl.load(filename)
else:
obj = eval(expression_obj)
jl.dump(obj,fname,compress = True)
return obj
示例调用:
rf_clf = saveobj(file, "rnd_cv.fit(X_train, np.ravel(y_train))", ignore_file=True)
错误:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-11-02c2cae43c5d> in <module>
1 file = Path("rf.pickle")
----> 2 rf_clf = saveobj(file, "rnd_cv.fit(X_train, np.ravel(y_train))", ignore_file=True)
~/Dropbox/myfnlib/util_funs.py in saveobj(filename, expression_obj, ignore_file)
37 obj = jl.load(filename)
38 else:
---> 39 obj = eval(expression_obj)
40 jl.dump(obj,fname,compress = True)
41 return obj
~/Dropbox/myfnlib/util_funs.py in <module>
NameError: name 'rnd_cv' is not defined
我猜,python 需要在本地评估函数,但由于该范围内不存在对象,因此会引发此错误。 有没有更好的方法来做到这一点。我需要重复执行此操作,这就是函数的原因。 非常感谢您的帮助。
【问题讨论】: