Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #20894

Re: pickle handling multiple objects ..

References <CAJ1erZ0s-aEzD_uYqY4=bhbwAkBRykXD72Lfx7bCmecRDazhAw@mail.gmail.com> <jid71t$eh6$1@dough.gmane.org>
Date 2012-02-27 00:00 +1100
Subject Re: pickle handling multiple objects ..
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.178.1330261239.3037.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, Feb 26, 2012 at 11:04 PM, Peter Otten <__peter__@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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: pickle handling multiple objects .. Chris Angelico <rosuav@gmail.com> - 2012-02-27 00:00 +1100
  Re: pickle handling multiple objects .. 88888 Dihedral <dihedral88888@googlemail.com> - 2012-02-27 06:00 -0800
  Re: pickle handling multiple objects .. 88888 Dihedral <dihedral88888@googlemail.com> - 2012-02-27 06:00 -0800

csiph-web