Most elegant way to store (persist) the value of a single (numeric) variable

1.1k views Asked by At

I need to store the value of a counter between executions of a script, so I can trigger a specific subroutine every hundred counts. I know I can write my integer into a text file and re-read it, and I know I can pickle my variable to much the same effect (the script currently uses the latter approach).

The concern I have is to find the approach that makes the code as elegant - simple and easily comprehensible - as possible, particularly to a non-technical audience.

The pickle module name is not helpful in that regard - once you grok the metaphor, it is entirely memorable, but if you don't know it, a comment (or verbal explanation) is required to explain that it is a module for serialising Python objects to disk.

Although 'nice to have', I'm not particularly concerned about the atomicity of the storage operation, nor about strongly protecting the stored value from loss [although I do need it to persist through a server reboot].

My interest is elegance of code to access and update the value of my variable, not the elegance of code to initialise whatever is storing the value (so, if the value were to be stored in a file, I'm interested in the code to read and write to a file that already exists and holds a value, not in creating the file on first execution).

What is the most elegant (and/or most pythonic) way to store a single (numeric) value so it persists between executions of a script?

3

There are 3 answers

2
a_guest On BEST ANSWER

The shelve module of the standard library was designed exactly for this use case: object persistence. Here you can simply do:

with shelve.open('counter') as db:
    db['value'] = counter

It will automatically create that file and store the value of the counter in it.

0
Peter Mabbott On

This is a take on a 'write to a text file' approach:

with open('counter', 'r') as f:
    value = int(f.read())
# Perform increments to the counter 'value' here
with open('counter', 'w') as f:
    f.write(str(value))

The loss of elegance here is the need to cast the variable from and to a str,but it is clear that you are writing and reading from a file on disk.

0
Peter Mabbott On

The pickle approach alluded to in my question is:

import pickle
with open('counter', 'rb') as f:
    value = pickle.load(f)    
# Perform increments to the counter 'value' here
with open('counter', 'wb') as f:
    pickle.dump(value, f)

The loss of elegance here is the need to know what the pickle module does.