Python Forum
is Path.samefile() always commutative? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: is Path.samefile() always commutative? (/thread-22019.html)



is Path.samefile() always commutative? - Skaperen - Oct-24-2019

is Path.samefile() always commutative? the documentation does not say. if both are symlinks, each pointing somewhere else, i'd think it would have to be commutative. but what if one of the paths is the actual file? can either be the actual file? does it even handle one of them being the actual file?


RE: is Path.samefile() always commutative? - DeaD_EyE - Oct-25-2019

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.