How to test if object is a pathlib path?

你说的曾经没有我的故事 提交于 2020-06-15 12:18:13

问题


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?


回答1:


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:

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.



来源:https://stackoverflow.com/questions/58647584/how-to-test-if-object-is-a-pathlib-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!