Search code examples
python-3.xpathlib

How to test if object is a pathlib path?


I want to test if obj is a pathlib path and realized that the condition type(obj) is pathlib.PosixPath will be False for a path generated on a Windows machine.

Thus the question, is there a way to test if an object is a pathlib path (any of the possible, Path, PosixPath, WindowsPath, or the Pure...-analogs) without checking for all 6 version explicitly?


Solution

  • Yes, using isinstance(). Some sample code:

    # Python 3.4+
    import pathlib
    
    path = pathlib.Path("foo/test.txt")
    # path = pathlib.PureWindowsPath(r'C:\foo\file.txt')
    
    # checks if the variable is any instance of pathlib
    if isinstance(path, pathlib.PurePath):
        print("It's pathlib!")
    
        # No PurePath
        if isinstance(path, pathlib.Path):
            print("No Pure path found here")
            if isinstance(path, pathlib.WindowsPath):
                print("We're on Windows")
            elif isinstance(path, pathlib.PosixPath):
                print("We're on Linux / Mac")
        # PurePath
        else:
            print("We're a Pure path")
    

    Why does isinstance(path, pathlib.PurePath) work for all types? Take a look at this diagram:

    PathLib overview

    We see that PurePath is at the top, that means everything else is a subclass of it. Therefore, we only have to check this one. Same reasoning for Path to check non-pure Paths.

    Bonus: You can use a tuple in isinstance(path, (pathlib.WindowsPath, pathlib.PosixPath)) to check 2 types at once.