我想测试一下obj是一个pathlib路径,并意识到条件type(obj) is pathlib.PosixPath将会是False用于在Windows计算机上生成的路径。
因此问题是,有没有一种方法来测试一个对象是否是pathlib路径(任何可能的,PathPosixPathWindowsPath,或Pure...-analogs)而不显式地检查所有6个版本?
发布于 2019-11-21 09:54:04
是的,使用isinstance()。一些示例代码:
# 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)适用于所有类型?请看下图:

我们看到了PurePath位于顶部,这意味着其他所有内容都是它的子类。因此,我们只需要检查这一个。同样的推理Path若要检查非纯路径,请执行以下操作。
奖金:您可以在以下位置使用元组isinstance(path, (pathlib.WindowsPath, pathlib.PosixPath))一次检查两种类型。
发布于 2021-02-26 17:07:12
我喜欢NumesSanguis answer,我是这样使用我学到的东西的:
def check_path_instance(obj: object, name: str) -> pathlib.Path:
""" Check path instance type then convert and return
:param obj: object to check and convert
:param name: name of the object to check (apparently there is no sane way to get the name of the variable)
:return: pathlib.Path of the object else exit the programe with critical error
"""
if isinstance(obj, (pathlib.WindowsPath, pathlib.PosixPath)):
return pathlib.Path(obj)
else:
if isinstance(obj, str):
return pathlib.Path(str(obj))
else:
logging.critical(
f'{name} type is: {type(obj)}, not pathlib.WindowsPath or pathlib.PosixPath or str')
)
sys.exit(1)https://stackoverflow.com/questions/58647584
复制相似问题