-class persistent_autoloaded_singleton(Persistent):
- """This class is meant to be used as a decorator around a class that:
-
- 1. Is a singleton; one global instance per python program.
- 2. Has a complex state that is initialized fully by __init__()
- 3. Would benefit from caching said state on disk and reloading
- it on future invokations rather than recomputing and
- reinitializing.
-
- Here's and example usage pattern:
-
- @persistent_autoloaded_singleton(
- filename = "my_cache_file.bin",
- may_reuse_persisted = reuse_if_mtime_less_than_limit_sec(60),
- persist_at_shutdown = PersistAtShutdown.IF_NOT_INITIALIZED_FROM_DISK,
- )
- class MyComplexObject(object):
- def __init__(self, ...):
- # do a bunch of work to fully initialize this instance
-
- def another_method(self, ...):
- # use the state stored in this instance to do some work
-
- What does this do, exactly?
-
- 1. Anytime you attempt to instantiate MyComplexObject you will
- get the same instance. This class is now a singleton.
- 2. The first time you attempt to instantiate MyComplexObject
- the wrapper scaffolding will check "my_cache_file.bin". If
- it exists and any may_reuse_persisted predicate indicates
- that reusing persisted state is allowed, we will skip the
- call to __init__ and return an unpickled instance read from
- the disk file. In the example above the predicate allows
- reuse of saved state if it is <= 60s old.
- 3. If the file doesn't exist or the predicate indicates that
- the persisted state cannot be reused (e.g. too stale),
- MyComplexObject's __init__ will be invoked and will be
- expected to fully initialize the instance.
- 4. At program exit time, depending on the value of the
- persist_at_shutdown parameter, the state of MyComplexObject
- will be written to disk using the same filename so that
- future instances may potentially reuse saved state. Note
- that the state that is persisted is the state at program
- exit time. In the example above this parameter indicates
- that we should persist state so long as we were not
- initialized from cached state on disk.
+class persistent_autoloaded_singleton(object):
+ """A decorator that can be applied to a Persistent subclass (i.e. a
+ class with a save() and load() method. It will intercept attempts
+ to instantiate the class via it's c'tor and, instead, invoke the
+ class' load() method to give it a chance to read state from
+ somewhere persistent.
+
+ If load() fails (returns None), the c'tor is invoked with the
+ original args as a fallback.
+
+ Based upon the value of the optional argument persist_at_shutdown,
+ (NEVER, IF_NOT_LOADED, ALWAYS), the save() method of the class will
+ be invoked just before program shutdown to give the class a chance
+ to save its state somewhere.
+
+ The implementations of save() and load() and where the class
+ persists its state are details left to the Persistent
+ implementation.