Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does pathlib have both PurePath & Path?

More than an answer to the question, I am trying to learn how to make sense of the Official Python Documentation.

I understand that Path inherits from PurePath, but I am unable to understand when to use which and why there is PurePath & Path instead of one.

In the list of alternatives, most are suggesting Path while some are suggesting Pathlib.

I am looking at os.path.dirname() where they are suggesting PurePath.parent. But I am getting the same result when I run pathlib.PurePath(file).parent.name & pathlib.Path(file).parent.name.

So, why did they use PurePath for some & Path for most. Why did they not suggest Path.parent instead of PurePath.parent ?

like image 237
user7579349 Avatar asked Aug 05 '19 03:08

user7579349


People also ask

What does Pathlib path () do?

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.

How does the Pathlib module represent paths?

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.

What is PurePath in Python?

Pure paths. Pure path objects provide path-handling operations which don't actually access a filesystem. There are three ways to access these classes, which we also call flavours: class pathlib. PurePath (*pathsegments)

What is the main difference between the Pathlib and os libraries?

The OS library will return a string, whereas the Pathlib will return an object of PosixPath. The benefit of having PosixPath returned is that we can directly use the returned object to do a lot more further operations.


1 Answers

First paragraph in pathlib documentation states:

Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.

Pure path objects provide path-handling operations which don’t actually access a filesystem.

Concrete paths are subclasses of the pure path classes. In addition to operations provided by the former(pure path), they also provide methods to do system calls on path objects.


In conclusion, PurePath acts like string (remove parts of path, join with another path, get parents etc). To remove directory, search directory, create a file or write to file, you must use Path object.

like image 77
Dinko Pehar Avatar answered Oct 13 '22 05:10

Dinko Pehar