Source code for saveable_objects.extensions._extensions
1from typing import Optional, TypeVar, Generic
2
3from .. import SaveableObject
4from .._meta_class import SaveAfterInitMetaClass
5
6T = TypeVar("T")
7
8class MetaSaveableWrapper(SaveAfterInitMetaClass):
9 """A metaclass for the :class:`SaveableWrapper` class.`
10 """
11 def __call__(cls, class_to_wrap: Optional[type] = None, path: Optional[str] = None):
12 instance = type.__call__(cls, class_to_wrap, path)
13 if class_to_wrap is None:
14 return instance
15 else:
16 return instance[class_to_wrap]
17
[docs]
18class SaveableWrapper(Generic[T], SaveableObject, metaclass=MetaSaveableWrapper):
19 """A template class for converting a general class to a
20 :class:`SaveableObject <saveable_objects.SaveableObject>`. For example a
21 class ``T`` can be made into a new Saveable class ``SaveableT`` in any of
22 the following ways:
23
24 .. code-block:: python
25
26 SaveableT = SaveableWrapper[T];
27 SaveableT = SaveableWrapper(T, path="default_path.pkl")
28 SaveableT = SaveableWrapper(path="default_path.pkl")[T];
29
30 A default path for the
31 :class:`SaveableObject <saveable_objects.SaveableObject>` can be set with
32 the ``path`` argument if parentheses are used.
33
34 The new class ``SaveableT`` will inherited from both ``T`` and
35 :class:`SaveableObject <saveable_objects.SaveableObject>`.
36 """
37 @staticmethod
38 def _get_class(arg: type, path_initialiser: Optional[str] = None):
39 class SaveableWrapped(arg, SaveableObject):
40 """Initialises the object of type ``T`` and next the
41 ``SaveableObject`` so that the initialisation of ``T`` is saved to
42 the file at ``path``.
43
44 Parameters
45 ----------
46 *args
47 The arguments to pass to the initialisation.
48 path : str, optional
49 File path to save the object to. If ``None`` then the object is
50 not saved. By default ``path_initialiser``
51 **kwargs
52 The keyword arguments to pass to the initialisation.
53 """
54 def __init__(self, *args, path: Optional[str] = path_initialiser, **kwargs):
55 arg.__init__(self, *args, **kwargs)
56 SaveableObject.__init__(self, path)
57 return SaveableWrapped
58 def __class_getitem__(cls, arg: type):
59 return cls._get_class(arg)
60 def __getitem__(self, arg: type):
61 return self._get_class(arg, self.default_path)
62 def __call__(self, arg: type):
63 return self._get_class(arg, self.default_path)
64 def __init__(self, class_to_wrap: Optional[type] = None, path: Optional[str] = None):
65 self.default_path = path
66 SaveableObject.__init__(self, None)