I would like to store a class and many instances for later use, or to give to someone else.
So far I can pickle and recover the instances, but I have to recreate the class by hand before loading them.
I've looked at this documentation which leads me to believe I should be able to do this somehow, but I can't seem to find out exactly how to do it.
EDIT: I've read this answer discussing the use of dill
(see this answer also), but I don't have dill
installed. I'd like a pickle solution if it exists.
import numpy as np
import pickle
class wow(object):
def __init__(self, x):
self.x = x
w5 = wow(np.arange(5))
w3 = wow(range(3))
with open("w5w3.pickle", "w") as outfile:
pickle.dump([w5, w3], outfile)
# save the class also
with open("wow.pickle", "w") as outfile:
pickle.dump(wow, outfile)
# OK, now delete class wow, then try to recover the pickles
del wow, w3, w5
try:
with open("wow.pickle", "r") as infile:
wow = pickle.load(infile)
except Exception, e: # returns: "'module' object has no attribute 'wow'"
print str(e)
print "so manually recreate class wow"
class wow(object):
def __init__(self, x):
self.x = x
with open("w5w3.pickle", "r") as infile:
W = pickle.load(infile)
for thing in W:
print type(thing.x), thing.x