Source code for saveable_objects.extensions._extensions
1fromtypingimportOptional,TypeVar,Generic 2 3from..importSaveableObject 4from.._meta_classimportSaveAfterInitMetaClass 5 6T=TypeVar("T") 7 8classMetaSaveableWrapper(SaveAfterInitMetaClass): 9"""A metaclass for the :class:`SaveableWrapper` class.`10 """11def__call__(cls,class_to_wrap:Optional[type]=None,path:Optional[str]=None):12instance=type.__call__(cls,class_to_wrap,path)13ifclass_to_wrapisNone:14returninstance15else:16returninstance[class_to_wrap]17
[docs]18classSaveableWrapper(Generic[T],SaveableObject,metaclass=MetaSaveableWrapper):19"""A template class for converting a general class to a20 :class:`SaveableObject <saveable_objects.SaveableObject>`. For example a21 class ``T`` can be made into a new Saveable class ``SaveableT`` in any of22 the following ways:2324 .. code-block:: python2526 SaveableT = SaveableWrapper[T];27 SaveableT = SaveableWrapper(T, path="default_path.pkl")28 SaveableT = SaveableWrapper(path="default_path.pkl")[T];2930 A default path for the31 :class:`SaveableObject <saveable_objects.SaveableObject>` can be set with32 the ``path`` argument if parentheses are used.3334 The new class ``SaveableT`` will inherited from both ``T`` and35 :class:`SaveableObject <saveable_objects.SaveableObject>`.36 """37@staticmethod38def_get_class(arg:type,path_initialiser:Optional[str]=None):39classSaveableWrapped(arg,SaveableObject):40"""Initialises the object of type ``T`` and next the41 ``SaveableObject`` so that the initialisation of ``T`` is saved to42 the file at ``path``.4344 Parameters45 ----------46 *args47 The arguments to pass to the initialisation.48 path : str, optional49 File path to save the object to. If ``None`` then the object is50 not saved. By default ``path_initialiser``51 **kwargs52 The keyword arguments to pass to the initialisation.53 """54def__init__(self,*args,path:Optional[str]=path_initialiser,**kwargs):55arg.__init__(self,*args,**kwargs)56SaveableObject.__init__(self,path)57returnSaveableWrapped58def__class_getitem__(cls,arg:type):59returncls._get_class(arg)60def__getitem__(self,arg:type):61returnself._get_class(arg,self.default_path)62def__call__(self,arg:type):63returnself._get_class(arg,self.default_path)64def__init__(self,class_to_wrap:Optional[type]=None,path:Optional[str]=None):65self.default_path=path66SaveableObject.__init__(self,None)