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?
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With