MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / save_obj

Function save_obj

monai/utils/misc.py:648–693  ·  view source on GitHub ↗

Save an object to file with specified path. Support to serialize to a temporary file first, then move to final destination, so that files are guaranteed to not be damaged if exception occurs. Args: obj: input object data to save. path: target file path to save the i

(
    obj: object,
    path: PathLike,
    create_dir: bool = True,
    atomic: bool = True,
    func: Callable | None = None,
    **kwargs: Any,
)

Source from the content-addressed store, hash-verified

646
647
648def save_obj(
649 obj: object,
650 path: PathLike,
651 create_dir: bool = True,
652 atomic: bool = True,
653 func: Callable | None = None,
654 **kwargs: Any,
655) -> None:
656 """
657 Save an object to file with specified path.
658 Support to serialize to a temporary file first, then move to final destination,
659 so that files are guaranteed to not be damaged if exception occurs.
660
661 Args:
662 obj: input object data to save.
663 path: target file path to save the input object.
664 create_dir: whether to create dictionary of the path if not existing, default to `True`.
665 atomic: if `True`, state is serialized to a temporary file first, then move to final destination.
666 so that files are guaranteed to not be damaged if exception occurs. default to `True`.
667 func: the function to save file, if None, default to `torch.save`.
668 kwargs: other args for the save `func` except for the checkpoint and filename.
669 default `func` is `torch.save()`, details of other args:
670 https://pytorch.org/docs/stable/generated/torch.save.html.
671
672 """
673 path = Path(path)
674 check_parent_dir(path=path, create_dir=create_dir)
675 if path.exists():
676 # remove the existing file
677 os.remove(path)
678
679 if func is None:
680 func = torch.save
681
682 if not atomic:
683 func(obj=obj, f=path, **kwargs)
684 return
685 try:
686 # writing to a temporary directory and then using a nearly atomic rename operation
687 with tempfile.TemporaryDirectory() as tempdir:
688 temp_path: Path = Path(tempdir) / path.name
689 func(obj=obj, f=temp_path, **kwargs)
690 if temp_path.is_file():
691 shutil.move(str(temp_path), path)
692 except PermissionError: # project-monai/monai issue #3613
693 pass
694
695
696def label_union(x: list | np.ndarray) -> list:

Callers 1

save_stateFunction · 0.90

Calls 2

check_parent_dirFunction · 0.85
removeMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…