3 """A Persistent is just a class with a load and save method. This
4 module defines the Persistent base and a decorator that can be used to
5 create a persistent singleton that autoloads and autosaves."""
12 from abc import ABC, abstractmethod
13 from typing import Any
17 logger = logging.getLogger(__name__)
20 class Persistent(ABC):
22 A base class of an object with a load/save method. Classes that are
23 decorated with @persistent_autoloaded_singleton should subclass this
24 and implement their save() and load() methods.
29 def save(self) -> bool:
31 Save this thing somewhere that you'll remember when someone calls
32 load() later on in a way that makes sense to your code.
41 Load this thing from somewhere and give back an instance which
42 will become the global singleton and which will may (see
43 below) be save()d at program exit time.
45 Oh, in case this is handy, here's how to write a factory
46 method that doesn't call the c'tor in python:
49 def load_from_somewhere(cls, somewhere):
50 # Note: __new__ does not call __init__.
51 obj = cls.__new__(cls)
53 # Don't forget to call any polymorphic base class initializers
54 super(MyClass, obj).__init__()
56 # Load the piece(s) of obj that you want to from somewhere.
57 obj._state = load_from_somewhere(somewhere)
64 def was_file_written_today(filename: str) -> bool:
65 """Returns True if filename was written today."""
67 if not file_utils.does_file_exist(filename):
70 mtime = file_utils.get_file_mtime_as_datetime(filename)
71 assert mtime is not None
72 now = datetime.datetime.now()
73 return mtime.month == now.month and mtime.day == now.day and mtime.year == now.year
76 def was_file_written_within_n_seconds(
80 """Returns True if filename was written within the pas limit_seconds
84 if not file_utils.does_file_exist(filename):
87 mtime = file_utils.get_file_mtime_as_datetime(filename)
88 assert mtime is not None
89 now = datetime.datetime.now()
90 return (now - mtime).total_seconds() <= limit_seconds
93 class PersistAtShutdown(enum.Enum):
95 An enum to describe the conditions under which state is persisted
96 to disk. See details below.
105 class persistent_autoloaded_singleton(object):
106 """A decorator that can be applied to a Persistent subclass (i.e. a
107 class with a save() and load() method. It will intercept attempts
108 to instantiate the class via it's c'tor and, instead, invoke the
109 class' load() method to give it a chance to read state from
110 somewhere persistent.
112 If load() fails (returns None), the c'tor is invoked with the
113 original args as a fallback.
115 Based upon the value of the optional argument persist_at_shutdown,
116 (NEVER, IF_NOT_LOADED, ALWAYS), the save() method of the class will
117 be invoked just before program shutdown to give the class a chance
118 to save its state somewhere.
120 The implementations of save() and load() and where the class
121 persists its state are details left to the Persistent
129 persist_at_shutdown: PersistAtShutdown = PersistAtShutdown.IF_NOT_LOADED,
131 self.persist_at_shutdown = persist_at_shutdown
134 def __call__(self, cls: Persistent):
135 @functools.wraps(cls) # type: ignore
136 def _load(*args, **kwargs):
138 # If class has already been loaded, act like a singleton
139 # and return a reference to the one and only instance in
141 if self.instance is not None:
143 'Returning already instantiated singleton instance of %s.', cls.__name__
147 # Otherwise, try to load it from persisted state.
149 logger.debug('Attempting to load %s from persisted state.', cls.__name__)
150 self.instance = cls.load()
151 if not self.instance:
152 msg = 'Loading from cache failed.'
154 logger.debug('Attempting to instantiate %s directly.', cls.__name__)
155 self.instance = cls(*args, **kwargs)
157 logger.debug('Class %s was loaded from persisted state successfully.', cls.__name__)
160 assert self.instance is not None
162 if self.persist_at_shutdown is PersistAtShutdown.ALWAYS or (
163 not was_loaded and self.persist_at_shutdown is PersistAtShutdown.IF_NOT_LOADED
165 logger.debug('Scheduling a deferred called to save at process shutdown time.')
166 atexit.register(self.instance.save)