Sometimes it's very easy to look in the implementation and understand how it works.
Path.samefile uses
stat
to compare files. If the stat result is different, it's a different file.
If you point a Path to a symlink and the other one to the file, where the symlink points to, you get
a different stat result.
Comparing a path of equality is different. There are all parts of the path compared.
>>> print(getsource(Path.samefile))
def samefile(self, other_path):
"""Return whether other_path is the same or not as this file
(as returned by os.path.samefile()).
"""
st = self.stat()
try:
other_st = other_path.stat()
except AttributeError:
other_st = os.stat(other_path)
return os.path.samestat(st, other_st)
>>> print(getsource(Path.__eq__))
def __eq__(self, other):
if not isinstance(other, PurePath):
return NotImplemented
return self._cparts == other._cparts and self._flavour is other._flavour
The os.path.samestat source code:
>>> print(getsource(os.path.samestat))
def samestat(s1, s2):
"""Test whether two stat buffers reference the same file"""
return (s1.st_ino == s2.st_ino and
s1.st_dev == s2.st_dev)
It takes the st_struct (stat result) and compares
st_ino
, which should be the inode number on the file system and the
st_dev
(device). So it's even not possible get a false positive on a duplicated file system.