0

I have a pickle file that I need to load from another project. It seems that the folder structure of that project is a little different. i.e: The model class was defined in main, but in my project, it put in "model.fraud_model.py". So when I try to load the pickle file, I get this exception:

'module' object has no attribute 'FraudModel'

I'm trying to modify the pickle file from this:

ccopy_reg
_reconstructor
p0
(c__main__
FraudModel

To this:

ccopy_reg
_reconstructor
p0
(cmodel.fraud_model
FraudModel

And it works. But this solution will change pickle file. I don't want this. So I import by hand:

from model.fraud_model import FraudModel
import sys
sys.modules['model.fraud_model'] = FraudModel

But it seems not work. Please help me how to fix this.

Thanks

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
Trần Kim Dự
  • 5,872
  • 12
  • 55
  • 107

1 Answers1

2

The pickler is expecting to be able to find __main__.FraudModel, so you just need to modify the python environment to look like it did when the object was originally pickled.

You should be able to do it by adding the class to the __main__ module, which every python program will have

from model.fraud_model import FraudModel
import sys
sys.modules['__main__'].FraudModel = FraudModel

Then you can unpickle the file and it should find the class.

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
  • thanks. It works :D Can I ask 2 questions: 1) should we "unload" after unpickle. 2) How can at the code of generate pickle file fix this problem ? (i.e: hard code a module). Thanks. – Trần Kim Dự Apr 26 '18 at 19:05