In Python, how do I tie an on-disk JSON file to an in-process dictionary? In Python, how do I tie an on-disk JSON file to an in-process dictionary? json json

In Python, how do I tie an on-disk JSON file to an in-process dictionary?


well, since python itself has no signals-slots, I guess you can instead make your own dictionary class by inherit it from python dictionary. Class exactly like python dict, only in every method of it that can change dict values you will dump your json.

also you can use smth like PyQt4 QAbstractItemModel which has signals. And when it data changed signal will emitted, do your dumping - it will be only in one place, which is nice.

I know these two are sort of stupid ways, probably yea. :) If anyone knows better, go ahead and tell!


This is a developpement from aspect_mkn8rd' answer taking into account Gerrat's comments, but it is too long for a true comment.

You will need 2 special container classes emulating a list and a dictionnary. In both, you add a pointer to a top-level object and override the following methods :

  • __setitem__(self, key, value)
  • __delitem__(self, key)
  • __reversed__(self)

All those methods are called in modification and should have the top-level object to be written to disk.

In addition, __setitem__(self, key, value) should look if value is a list and wrap it into a special list object or if it is a dictionary, wrap it into a special dictionnary object. In both case, the method should set the top-level object into the new container. If neither of them and the object defines __setitem__, it should raise an Exception saying the object is not supported. Of course you should then modify the method to take in account this new class.

Of course, there is a good deal of code to write and test, but it should work - left to the reader as an exercise :-)


If concurrency is not required, maybe consider writing 2 functions to read and write the data to a shelf file? Our is the idea to have the dictionary" aware" of changes to update the file without this kind of thing?