Created
December 4, 2025 09:05
-
-
Save Turin86/17ed041c5cfd07a4a4dff64b75b17e26 to your computer and use it in GitHub Desktop.
Python temporary persistent dicts leveraging the dbm module
This file contains hidden or 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
| #!/usr/bin/env python3 | |
| from collections.abc import MutableMapping | |
| import dbm | |
| import json | |
| import os | |
| from tempfile import TemporaryDirectory | |
| tmpdir = None | |
| class PersistentTemporaryDict(MutableMapping): | |
| def __init__(self, slug): | |
| global tmpdir | |
| if tmpdir is None: | |
| tmpdir = TemporaryDirectory() | |
| filename = '{}.dbm'.format(slug) | |
| filepath = os.path.join(tmpdir.name, filename) | |
| self.db = dbm.open(filepath, flag='c') | |
| def close(self): | |
| self.db.close() | |
| def encode(self, item): | |
| if isinstance(item, (int,)): | |
| item = (str(item),) | |
| elif isinstance(item, (str,)): | |
| item = (item,) | |
| return json.dumps(item) | |
| def decode(self, item): | |
| item = json.loads(item) | |
| if len(item) == 1: | |
| item = item[0] | |
| return item | |
| def __enter__(self): | |
| return self | |
| def __exit__(self, exc_type, exc_value, traceback): | |
| self.close() | |
| def __len__(self): | |
| return len(self.db) | |
| def __getitem__(self, key): | |
| item = self.decode(self.db[self.encode(key)].decode()) | |
| return item | |
| def __setitem__(self, key, value): | |
| self.db[self.encode(key)] = self.encode(value) | |
| def __delitem__(self, key): | |
| del self.db[self.encode(key)] | |
| def __missing__(self, key): | |
| raise KeyError | |
| def __iter__(self): | |
| return iter(self.decode(_.decode()) for _ in self.db.keys()) | |
| def __repr__(self): | |
| return repr(dict(self)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment