如何测试对象是否为pathlib路径? [英] How to test if object is a pathlib path?

查看:195
本文介绍了如何测试对象是否为pathlib路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试obj是否为pathlib路径,并意识到在Windows计算机上生成的路径的条件type(obj) is pathlib.PosixPath将为False.

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.

因此,问题是,有一种方法可以测试对象是否为pathlib路径(任何可能的PathPosixPathWindowsPathPure... -analogs),而不检查所有对象. 6版本明确?

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?

推荐答案

是,使用isinstance().一些示例代码:

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")

为什么isinstance(path, pathlib.PurePath)适用于所有类型?看一下这个图:

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

我们看到PurePath在顶部,这意味着其他所有内容都是它的子类.因此,我们只需要检查这一点. Path检查非纯路径的原因相同.

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.

奖金:您可以在isinstance(path, (pathlib.WindowsPath, pathlib.PosixPath))中使用元组一次检查两种类型.

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

这篇关于如何测试对象是否为pathlib路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆