Skip to content

Instantly share code, notes, and snippets.

@Imxset21
Created September 10, 2015 21:59
Show Gist options
  • Save Imxset21/dcfa90f0e1d31114c6ec to your computer and use it in GitHub Desktop.
Save Imxset21/dcfa90f0e1d31114c6ec to your computer and use it in GitHub Desktop.
"""
..module:: deltadict
:platform: Linux
:synopsis: Dictionary that saves old key values to disk
.. moduleauthor:: Pedro Rittner <pr273@cornell.edu>
"""
import tempfile
class DeltaDict(dict):
"""
Dictionary with 'write-through' semantics, using a file as backing storage
"""
def __init__(self, backing_file: str=None, **kwargs):
super().__init__(**kwargs)
self.file_p = None
# Either use backing file, if provided, or use a random tmp file
if backing_file is not None:
self.file_p = open(backing_file, 'w+')
else:
self.file_p = tempfile.TemporaryFile('w+')
def __setitem__(self, key, val):
self.file_p.write("{0} := {1}".format(str(key), str(val)))
super().__setitem__(key, val)
def __del__(self):
self.file_p.close()
def main():
""" Runs a small test """
my_dict = DeltaDict(backing_file="backing_file.txt")
my_dict[2] = 2
print(my_dict[2])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment