[Tutor] Pickling in plain English

jfouhy@paradise.net.nz jfouhy at paradise.net.nz
Wed May 25 01:32:50 CEST 2005


Quoting Tom Tucker <tktucker at gmail.com>:

> I am having trouble understanding the c|Pickle modules. What does 
> serializing and de-serializing objects mean? I have read the below
> urls and I "think" I understand the process, but I can't visualize the
> beneifts. Can someone kindly explain pickling in lamens terms?

It's actually astonishingly simple, once you get the hang of it.

example:

>>> arr = [1, 3, 5, 7]
>>> dct = {'foo':1, 'bar':2, 'baz':3}
>>> st = "re: your mail"
>>>
>>> import pickle
>>> f = file('dump', 'wb')
>>> pickle.dump((arr, dct, st), f)
>>> f.close()
>>> ^Z

[new instance of python]

>>> import pickle
>>> f = file('dump', 'r')
>>> res = pickle.load(f)
>>> res
([1, 3, 5, 7], {'bar': 2, 'foo': 1, 'baz': 3}, 're: your mail')

[and you can look at the file 'dump' on your HDD, if you want to]

Basically, pickle allows you to write any python object to disk and the load it
back again with very little effort.  This is important if you want your program
to be able to save state between instances.

You can pickle more complex objects; the only restriction is that pickle.load
must be able to find the module where the classes are defined.

[there are some other restrictions, but you can do a lot without worrying about
them]

Does this help?

-- 
John.


More information about the Tutor mailing list