import torch


def safe_save(obj, path, pickle_protocol=torch.serialization.DEFAULT_PROTOCOL):
    """
    Safely saves obj in path by creating .tmp file
    before ovewriting an existing file

    Parameters
    ----------
    obj : object
        the object to be saved
    path : str
        the path where to save obj
    pickle_protocol : int (optional)
        The pickle protocol to uses. By default, the torch default_protocol
        is used.
    
    Returns
    -------
    obj : object
        the same obj received as input

    """
    with open(path, 'wb') as f:
        torch.save(obj, f, pickle_protocol=pickle_protocol)
    return obj