Exploring the Finer Details of Path
00:00 The Finer Details of Path. In this section of the course, you’ll take a look at some of the details of paths, which will help you understand them in more depth, starting out at looking at differences between operating systems.
This feature makes it fairly easy to write cross-platform compatible code. It is possible to ask for a
WindowsPath or a
PosixPath explicitly, but you will only be limiting your code to that system without any benefits.
There might be times when you need a representation of a path without access to the underlying file system, in which case it could also make sense to represent a Windows path on a non-Windows system or vice versa. This can be done with
You can directly instantiate
PurePosixPath on all systems. Instantiating
PurePath will return one of these objects depending on the operating system you’re using. Here,
PurePath is run on macOS … and here, on Windows.
At the start of the course, you saw that paths are not strings, and one motivation behind
pathlib is to represent the file system with proper objects. In fact, the documentation of
pathlib is titled pathlib — Object-oriented filesystem paths.
02:27 The object-oriented approach is already visible in the examples you’ve seen, but here you will see some other examples illustrating this. Independently of the operating system you’re using, paths are represented in Posix style, with the forward slash as the path separator. On Windows, you’ll see something similar to what’s seen on-screen.
This is particularly useful if you’re using a library that doesn’t know how to deal with
pathlib.Path objects. This is a bigger problem on Python versions before 3.6, but it’s something you may experience when working with older unmaintained libraries, which can happen when working with large, mature projects.
It’s considered best practice to use
os.fspath() instead of
str() if you need to do an explicit conversion. This is a little safer, as it will raise an error if you accidentally try to convert an object that is not pathlike, as seen on-screen.
Potentially the most controversial part of the
pathlib library is the use of the
/ operator. For a little peek under the hood, let’s see how that’s implemented. This is an example of operator overloading: the behavior of an operator is changed depending on the context.
You have seen this before. Think about how
+ means different things for strings and numbers. Python implements operator overloading through the use of double underscore methods, a.k.a. dunder methods.
/ operator is defined by the
.__truediv__() method. In fact, if you take a look at the source code of
pathlib, you’ll see the code seen on-screen, which implements the behavior you’ve already used.
Become a Member to join the conversation.