Skip to content

Loading

Loading an VIPicklable object

VIPicklable objects have a load method for loading an object instance :

>>> class MyClass(VIPicklable):
...    PICKLE_BLACKLIST = ["unpicklable_attribute"]
...
...    def __init__(self):
...        self.unpicklable_attribute = "do_not_pickle"
...
>>> obj = MyClass()
>>> obj.save("folder")
>>> obj = MyClass.load("folder")
VIPicklable.load

Load a VIPicklable instance.

Load a VIPicklable instance and all loadable attributes from a file or folder.

Parameters:

Name Type Description Default
path Union[str, Path]

Path to the pickle file

required
pickle_dump_kwargs dict

additionnal arguments to be pass to load_instance method. Default to None.

None

Raises:

Type Description
FileNotFoundError

Pickle file not found

Returns:

Name Type Description
VIPicklable VIPicklable

The instance object

Source code in /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/vipickle/mixin.py
@classmethod
def load(
    cls,
    path: Union[str, Path],
    pickle_dump_kwargs: dict = None,
) -> "VIPicklable":
    """Load a VIPicklable instance.

    Load a VIPicklable instance and all loadable attributes from a file or folder.

    Args:
        path (Union[str, Path]): Path to the pickle file
        pickle_dump_kwargs (dict, optional): additionnal arguments to be pass to
            load_instance method. Default to None.

    Raises:
        FileNotFoundError: Pickle file not found
    Returns:
        VIPicklable: The instance object
    """
    if isinstance(path, str):
        path = Path(path)

    if pickle_dump_kwargs is None:
        pickle_dump_kwargs = {}

    if path.is_dir():
        pickle_path = path / cls.PICKLE_NAME
        folder_path = path
    elif path.is_file():
        pickle_path = path
        folder_path = path.parent
    else:
        raise FileNotFoundError(f"{path} not found")

    cls.before_load()

    obj = cls.load_instance(pickle_path, **pickle_dump_kwargs)
    obj.load_pickle_blacklisted(folder_path)

    obj.after_load()
    return obj

Load hooks

Under the hood, the load method does the following :

stateDiagram-v2
    [*] --> self.before_load()
    self.before_load() --> self.load_instance()
    self.load_instance() --> self.load_pickle_blacklisted()
    self.load_pickle_blacklisted() --> self.after_load()
    self.after_load() --> [*]

One can redefine any of these methods to personnalise the saving process :