[英]Can't use pickled function inside a pytest test
So I have this scenario, I create a function
that depends on pandas
, which I then pickle
and then reload and try to run and gives error
that pd is not defined
:所以我有这种情况,我创建了一个依赖于
function
的pandas
,然后我对其进行pickle
,然后重新加载并尝试运行并给出pd is not defined
error
:
def pandize(arg):
pd.DataFrame('a')
import dill
with open('pandize.pkl', 'wb') as f:
dill.dump(pandize, f)
with open('pandize.pkl', 'rb') as f:
p = dill.load(f)
p(1)
NameError: name 'pd' is not defined
After that I import pandas as pd
and the code gets called.之后,我
import pandas as pd
并调用代码。
But I can't replicate this behaviour inside a pytest
test function.但我无法在
pytest
测试 function 中复制此行为。 Even if I add the import pandas as pd
I'm still getting the NameError
pd is not defined
.即使我将
import pandas as pd
我仍然收到NameError
pd is not defined
。 Any ideas why?任何想法为什么?
As pointed out by @MrBeanBremen in linked question in the comment, importing __main__
and then defining pandas
in __main__
made the trick:正如@MrBeanBremen在评论中的链接问题中指出的那样,导入
__main__
然后在__main__
中定义pandas
取得了成功:
import pandas as pd
import __main__
__main__.pd = pd
with open('pandize.pkl', 'rb') as f:
p = dill.load(f)
p(1)
This setup doesn't cause the test to fail with a NameError
any more.此设置不会再导致测试因
NameError
而失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.