Store a variable permanently

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Mar 11 06:19:49 EDT 2013



----- Original Message -----
> On Fri, 01 Mar 2013 11:19:22 +0100, Jean-Michel Pichavant wrote:
> 
> > ----- Original Message -----
> >> So i have a variable called funds that i want to store the value
> >> of
> >> even after the program is exited. My funds variable holds the
> >> total
> >> value of funds i have. I add a certain number of funds each time i
> >> run
> >> the program by entering how much i want to add. How would i store
> >> the
> >> funds variable to keep its value? --
> >> http://mail.python.org/mailman/listinfo/python-list
> >> 
> >> 
> > Hi,
> > 
> > I would serialize the data.
> > 
> > http://docs.python.org/2/library/pickle.html
> 
> 
> I don't think we should recommend to a newbie that they use pickle
> without even warning them that using pickle is insecure and dangerous
> if
> they are opening pickles from untrusted sources.
> 
> But for a single int, pickle too is overkill, and a simple
> human-readable
> and writable file is probably all that is needed:
> 
> def save_value(n, configfile='myconfig'):
>     if n != int(n):
>         raise ValueError('expected an int')
>     with open(configfile, 'w') as f:
>         f.write("value=%d" % n)
> 
> def load_value(configfile='myconfig'):
>     with open(configfile) as f:
>         s = f.read().strip()
>     a, b = s.split("=", 1)
>     if a.strip() != "value":
>         raise ValueError('invalid config file')
>     return int(b)
> 
> 
> Untested but ought to work.
> 
> 
> --
> Steven

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
.

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).
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.

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.


More information about the Python-list mailing list