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
:
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.
But I can't replicate this behaviour inside a pytest
test function. Even if I add the import pandas as pd
I'm still getting the 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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.