Path.replace 等同于 os.replace 或 shutil.move 吗?

Is Path.replace equivalent to os.replace or shutil.move?

pathlib.Path.replace 方法的文档指出:

Rename this file or directory to the given target. If target points to an existing file or directory, it will be unconditionally replaced.

这缺少一点细节。为了比较,这里是 os.replace:

的文档

Rename the file or directory src to dst. If dst is a directory, OSError will be raised. If dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

重要的部分是 "The operation may fail if src and dst are on different filesystems"。不像os.replaceshutil.move没有这个问题:

If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied to dst using copy_function and then removed.

那么,Path.replace 使用的是这些函数中的哪一个?是否存在 Path.replace 失败的风险,因为目标位于不同的文件系统上?

Path(x).replace(y) 只是调用 os.replace(x, y)。你可以在 the source code:

中看到这个
class _NormalAccessor(_Accessor):
    # [...]
    replace = os.replace
    # [...]

_normal_accessor = _NormalAccessor()

# [...]

class Path(PurePath):
    # [...]
    def _init(self,
              # Private non-constructor arguments
              template=None,
              ):
        self._closed = False
        if template is not None:
            self._accessor = template._accessor
        else:
            self._accessor = _normal_accessor

    # [...]

    def replace(self, target):
        """
        Rename this path to the given path, clobbering the existing
        destination if it exists.
        """
        if self._closed:
            self._raise_closed()
        self._accessor.replace(self, target)