Search code examples
pythonzen-of-python

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


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?


Solution

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