Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 395
Matthias Arras Avatar asked Oct 31 '19 16:10

Matthias Arras


People also ask

What is Pathlib path?

The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.

Is Pathlib better than os?

With Pathlib, you can do all the basic file handling tasks that you did before, and there are some other features that don't exist in the OS module. The key difference is that Pathlib is more intuitive and easy to use. All the useful file handling methods belong to the Path objects.

How does path from Pathlib work?

With pathlib , file paths can be represented by proper Path objects instead of plain strings as before. These objects make code dealing with file paths: Easier to read, especially because / is used to join paths together. More powerful, with most necessary methods and properties available directly on the object.

How does the Pathlib module represent paths?

The Pathlib module can deal with absolute as well as relative paths. An absolute path begins from the root directory and specifies the complete directory tree, whereas a relative path, as the name suggests, is the path of a file relative to another file or directory (usually the current directory).


1 Answers

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.

like image 138
NumesSanguis Avatar answered Nov 12 '22 03:11

NumesSanguis