pickle handling multiple objects ..

88888 Dihedral dihedral88888 at googlemail.com
Mon Feb 27 09:00:22 EST 2012


在 2012年2月26日星期日UTC+8下午9时00分31秒,Chris Angelico写道:
> 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

I love python for pickle and zip lib build in. I write programs that 
stay in the L1 or L2 cache of the CPU > 97% percent of chance of nontrivial executions.



More information about the Python-list mailing list