Created
September 10, 2015 21:59
-
-
Save Imxset21/dcfa90f0e1d31114c6ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
..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