Skip to content

Instantly share code, notes, and snippets.

@gubser gubser/
Last active May 17, 2018

What would you like to do?
License: MIT
import json
import time
import logging
from collections import UserDict
class AutoReloadConfig(UserDict):
A dictionary that automatically reloads itself from a file.
On each call to __getitem__(), check if config is older than reload_period and if yes then reload from file.
# load from config.json every 60s
config = AutoReloadConfig("config.json", 60)
# gets value from config (and reloads beforehand if last get was before 60s)
test = config["test"]
def __init__(self, config_filename, reload_period = 60):
self._logger = logging.getLogger("config")
self._reload_period = reload_period
self._filename = config_filename
self._age = 0
def __getitem__(self, key):
if self._age + self._reload_period < time.time():
return super().__getitem__(key)
def _reload(self):
with open(self._filename) as fp:
config = json.load(fp)
self._age = time.time()
# set data used by UserDict = config
self._logger.debug("config reloaded")
self._logger.exception("failed to reload configuration from file \"" + self._filename + "\".")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.