Store a variable permanently

Steven D'Aprano steve+comp.lang.python at
Tue Mar 12 11:17:47 CET 2013

On Mon, 11 Mar 2013 11:19:49 +0100, Jean-Michel Pichavant wrote:

> While your point about security is fair, the others aren't. Pickle uses
> by default an ascii representation of the data, it's readable and
> writeable.
> import pickle
> a = 758
> pickle.dump(a, open('test.pickle', 'w')) 
> !cat test.pickle
> I758
> .

What is that? It's not Python code, !cat test.pickle gives a syntax error.

By the way, you can dump pickles directly to a string, which may be more 
convenient for demonstration purposes:

py> import pickle
py> pickle.dumps(758)

I take your point that a pickle of a simple int is relatively readable, 
although it does require care when editing. If you drop the dot, or the 
newline, or change the I to lowercase, or even merely add a space after 
the dot, bad things happen.

But yes, I will concede that a single pickled int is relatively readable. 
But that certainly isn't always the case:

py> pickle.dumps([])
py> pickle.dumps([None])

For even a *slightly* more complex example, the pickle turns into noise.

> I don't see how 1 line of code (+ the import) can be overkill versus the
> dozen untested lines you provide (I'm sure it's working, my point being
> pickle has already been tested). 

Pickle is a big module, over 1400 lines, capable of serialising almost 
anything. It's a big, powerful hammer for cracking armour-plated 
coconuts. But a single int is pretty much a peanut. Compare pickle's 1400 
lines with the dozen or so lines I provided. That is all that I meant by 

> More importantly, if the code evolve
> and you need to store 2 integers, or a tuple or anything else that is
> pickable, it costs you 0 dev if you're using pickle.

Sure. And once you move beyond a single value, the ability to call pickle 
"human readable and writable" decreases rapidly. Without using pickle, 
can you tell what this represents?



More information about the Python-list mailing list