8

I already run my code to load my variable saved by pickle. This my code

import pickle 
last_priors_file = open('simpanan/priors', 'rb') 
priors = pickle.load(last_priors_file)

and i get error like this : AttributeError: Can't get attribute 'Wishart' on <module '__main__' from 'app.py'>

Srikar Manthatti
  • 504
  • 2
  • 15
  • 2
    Your pickle references a class that doesn't exist in your current script. Did you move it to a different module, or are you using a different module as your script now? – Martijn Pieters May 17 '18 at 14:53
  • Put differently: do you have a `Wishart` class defined *anywhere* in your project right now? How did you create the pickle? – Martijn Pieters May 17 '18 at 14:53
  • 8
    Classes (and functions) are not pickled, only references to how to find the same class again in your program are stored. Instances then are loaded by creating a new instance of that class and loading unpickled data into the new instance. If you removed a class, then you can't load the pickle anymore. If the location of the class changed, you need to make the old location available to be able to unpickle the data again. That can be a simple as an extra reference to the same class. – Martijn Pieters May 17 '18 at 14:54
  • 2
    What if you modified the class after you pickled the object, then wanted to unpickle it into that same object? – bmc Sep 28 '18 at 13:19
  • @MartijnPieters Would you mind putting your comment as an answer? It has helped me at once while the answer here has not helped me. It was as simple as running the code that builds the class, without the need to create an object of it nor filling that object with "life" / data. Therefore, there is no need to do any calculations on the object, just load the class. – questionto42 Oct 06 '21 at 09:00

1 Answers1

5

This happens because the pickled data was saved when the script is run as __name__ == '__main__' and so it saves the location of Wishart as __main__.Wishart. Then, when you run your next script to load the data, there is no Wishart in scope so it fails.

The fix in this case is to simply add from wherever import Wishart before the call to pickle.load.

aconz2
  • 316
  • 3
  • 7