Reputation: 4346
I have a class instance which I dump in a .pickle file using pickle.dump(instance,outputfile)
. I can distribute the script and the pickle file and ask users to run the python script with the pickle file as an argument, and then I can load that instance using pickle.load(pickle_file_passed_as_argument)
Can I instead "embed" the pickle file inside the script itself, and then just pass the script around? Then, when users run the script I can load the instance of the "embedded" object and use all the object's member functions?
My question is similar to:
I didn't understand any of the answers given there as they're abstract descriptions of what to do, without code examples. I'm not sure how to use the triple-quote trick to embed objects (though all the answers in that question mention that). I've not used triple-quote strings like that before..
One of the answers mentions using s=pickle.dumps(objectInstance)
followed by pickle.loads(s)
and combine that with the triple quotes to embed the object. How exactly do I "combine" dumps,loads with the triple quotes trick, I don't get that part..
Upvotes: 1
Views: 1213
Reputation: 2026
What this answer means is to encode the data to be included with pickle
and encode
:
import pickle
data = dict(a=1,b=2)
pickle.dumps(data).encode('base64')
> 'KGRwMApTJ2EnCnAxCkkxCnNTJ2InCnAyCkkyCnMu\n'
and to decode it accordingly in your file to be shared from the string being written in the source code:
import pickle
# data encoded as a string
encoded_data = """KGRwMApTJ2EnCnAxCkkxCnNTJ2InCnAyCkkyCnMu\n"""
# decoding of the data
data = pickle.loads(encoded_data.decode('base64'))
print data
> {'a': 1, 'b': 2}
Upvotes: 3