pickle handling multiple objects ..

Chris Angelico rosuav at gmail.com
Sun Feb 26 14:00:31 CET 2012


On Sun, Feb 26, 2012 at 11:04 PM, Peter Otten <__peter__ at web.de> wrote:
> This is however a bit errorprone. If you accidentally write the loading code
> as
>
> fruit, beverages, vegetables = pickle.load(f)
>
> you'll end up drinking potatoes.

You mean vodka? :)

Additionally, you'll get a weird crash out of your program if load()
returns something other than a sequence of length 3. Remember,
everything that comes from outside your code is untrusted, even if you
think you made it just two seconds ago.

Of course, sometimes that exception is absolutely correct. If you wrap
all this in an exception handler that gives some reasonable behaviour
- which might even be "terminate the program with a traceback", which
is the default - then it's fine to let it throw on failure, and
anything else is just a waste of effort. But for maximum
extensibility, you would want to make it so that you can add more
elements to what you save without your code breaking on an old save
file - and that's where the dictionary is far better. A slight tweak,
though:

data = pickle.load(f)
fruit = data.get("fruit",[])
beverages = data.get("beverages",[])
vegetables = data.get("vegetables",[])

With this, you guarantee that (a) unrecognized keys will be safely
ignored, and (b) absent keys will quietly go to their given defaults.

ChrisA



More information about the Python-list mailing list