Creating a SaveableObject¶
At the heart of saveable-objects lies the class SaveableObject. There are several ways to create a SaveableObjects which we will outline here:
Throughout this tutorial we will consider converting the class
class A():
pass
to a saveable-object.
Inheritance¶
You can design a class to be a saveable-object from the ground up via inheritance. To achieve this you must do two things:
Inherit
SaveableObjectAdd
pathas a keyword arguement to the__init__function:
For example,
from saveable_objects import SaveableObject
class A(SaveableObject):
def __init__(self, path: Optional[str] = None):
super().__init__(path)
Note if you forget step 2., i.e., For example,
from saveable_objects import SaveableObject
class A(SaveableObject):
def __init__(self):
super().__init__("fixed_path.pkl")
the code will crash. This is because the path variable is intercepted from
Decorating¶
A less intrusive but less transparent method is to decorate the definition of A with SaveableWrapper:
from saveable_objects.extensions import SaveableWrapper
@SaveableWrapper
class A():
pass
We can also pass a default path as follows:
from saveable_objects.extensions import SaveableWrapper
@SaveableWrapper(path="default_path.pkl")
class A():
pass
Note that under the hood this will result in a slightly different inheritance structure than achieved via the inheritance method. Specifically the decorator generates a new class that will be called A that inherits the old A and SaveableObject.
Wrapping¶
Sometimes you might import A from a package or other code you don’t wish to modify. A consise solution to this is to wrap the class A using SaveableWrapper:
from saveable_objects.extensions import SaveableWrapper
A = SaveableWrapper[A];
We can also pass a default path as follows:
from saveable_objects.extensions import SaveableWrapper
A = SaveableWrapper(path="default_path.pkl")[A];
Note, just as with decoration method, under the hood this will result in a slightly different inheritance structure than achieved via the Inheritance method. Specifically the decorator generates a new class that will be called A that inherits the old A and SaveableObject.