Here’s the same example regarding class definition and object pickling:
import pickle
class Cucumber:
def __init__(self):
self.size = 'small'
def get_size(self):
return self.size
cucu = Cucumber()
with open('cucumber.pckl', 'wb') as file_out:
pickle.dump(cucu, file_out)
We see no errors, so we might conclude that the Cucumber
class and object were pickled successfully, and now we can retrieve them from the file. In fact, only the object is persisted but not its definition allowing us to determine the attribute layout:
If you run the code, you receive:
Traceback (most recent call last):
File "main.py", line 4, in <module>
data = pickle.load(file_in)
AttributeError: Can't get attribute 'Cucumber' on <module '__main__' from 'main.py'>
output
The remedy for the above problems is: the code that calls the load()
or loads()
functions of pickle
should already know the function/class definition.