1

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:

This question

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..

2
  • Why don't you just embed the object as ordinary Python code (e.g. by using repr to dump Python code for the instance)? It will be clearer than a giant pickle blob in your code. Commented Oct 22, 2015 at 19:24
  • @nneonneo Can you illustrate an example of doing that?.. Thanks! Commented Oct 22, 2015 at 19:28

1 Answer 1

3

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.