8 from abc import ABC, abstractmethod
13 logger = logging.getLogger(__name__)
16 class Persistent(ABC):
18 A base class of an object with a load/save method. Classes that are
19 decorated with @persistent_autoloaded_singleton should subclass this
20 and implement their save() and load() methods.
25 def save(self) -> bool:
27 Save this thing somewhere that you'll remember when someone calls
28 load() later on in a way that makes sense to your code.
37 Load this thing from somewhere and give back an instance which
38 will become the global singleton and which will may (see
39 below) be save()d at program exit time.
41 Oh, in case this is handy, here's how to write a factory
42 method that doesn't call the c'tor in python:
45 def load_from_somewhere(cls, somewhere):
46 # Note: __new__ does not call __init__.
47 obj = cls.__new__(cls)
49 # Don't forget to call any polymorphic base class initializers
50 super(MyClass, obj).__init__()
52 # Load the piece(s) of obj that you want to from somewhere.
53 obj._state = load_from_somewhere(somewhere)
60 def was_file_written_today(filename: str) -> bool:
61 """Returns True if filename was written today."""
63 if not file_utils.does_file_exist(filename):
66 mtime = file_utils.get_file_mtime_as_datetime(filename)
67 assert mtime is not None
68 now = datetime.datetime.now()
69 return mtime.month == now.month and mtime.day == now.day and mtime.year == now.year
72 def was_file_written_within_n_seconds(
76 """Returns True if filename was written within the pas limit_seconds
80 if not file_utils.does_file_exist(filename):
83 mtime = file_utils.get_file_mtime_as_datetime(filename)
84 assert mtime is not None
85 now = datetime.datetime.now()
86 return (now - mtime).total_seconds() <= limit_seconds
89 class PersistAtShutdown(enum.Enum):
91 An enum to describe the conditions under which state is persisted
92 to disk. See details below.
101 class persistent_autoloaded_singleton(object):
102 """A decorator that can be applied to a Persistent subclass (i.e. a
103 class with a save() and load() method. It will intercept attempts
104 to instantiate the class via it's c'tor and, instead, invoke the
105 class' load() method to give it a chance to read state from
106 somewhere persistent.
108 If load() fails (returns None), the c'tor is invoked with the
109 original args as a fallback.
111 Based upon the value of the optional argument persist_at_shutdown,
112 (NEVER, IF_NOT_LOADED, ALWAYS), the save() method of the class will
113 be invoked just before program shutdown to give the class a chance
114 to save its state somewhere.
116 The implementations of save() and load() and where the class
117 persists its state are details left to the Persistent
125 persist_at_shutdown: PersistAtShutdown = PersistAtShutdown.IF_NOT_LOADED,
127 self.persist_at_shutdown = persist_at_shutdown
130 def __call__(self, cls: Persistent):
131 @functools.wraps(cls) # type: ignore
132 def _load(*args, **kwargs):
134 # If class has already been loaded, act like a singleton
135 # and return a reference to the one and only instance in
137 if self.instance is not None:
139 f'Returning already instantiated singleton instance of {cls.__name__}.'
143 # Otherwise, try to load it from persisted state.
145 logger.debug(f'Attempting to load {cls.__name__} from persisted state.')
146 self.instance = cls.load()
147 if not self.instance:
148 msg = 'Loading from cache failed.'
150 logger.debug(f'Attempting to instantiate {cls.__name__} directly.')
151 self.instance = cls(*args, **kwargs)
154 f'Class {cls.__name__} was loaded from persisted state successfully.'
158 assert self.instance is not None
160 if self.persist_at_shutdown is PersistAtShutdown.ALWAYS or (
162 and self.persist_at_shutdown is PersistAtShutdown.IF_NOT_LOADED
165 'Scheduling a deferred called to save at process shutdown time.'
167 atexit.register(self.instance.save)