Python Forum
is Path.samefile() always commutative?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
is Path.samefile() always commutative?
#2
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: is Path.samefile() always commutative? - by DeaD_EyE - Oct-25-2019, 07:39 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020