PetMetz
PetMetz

Reputation: 85

Why doesn't pathlib.Path implement __add__?

Premise

A convenient but fragile path might be written in Python as a string

fdir = r'mydir/'
fname = r'myfile'
fpath = fdir + fname

This is a terrible practice (np.inf demerits), but the syntax is concise and readable (+1 merits).

Question

Should pathlib.Path have implemented an __add__ method, which would amount to a little syntactic sugar.

pathlib.Path stores path elements internally as a tuple and constructs representations on demand, right? In theory, this shouldn't break anything within the class-- the __add__ method would simply internally self.joinpath(other).

Why wasn't this done, and what about this is unpythonic?

Example

BASE = pathlib.Path('').resolve()  # some working directory
...
for fstring, stuff in zip(flist, queue):  # some stuff to output to file
   with open(BASE + fstring, 'w+') as f:  # <--- this is compact and readable
      f.write(stuff)

Here, the common task of appending to a path is represented as BASE + string, which is just prettier than BASE.joinpath(string)

An uglier example (I don't know why you would do this, but bear with me):

s1 = 'components'
s2 = 'arms'
s3 = 'bones'
s4 = 'humerus'

fpath = Path(s1).joinpath(s2).joinpath(s3).joinpath(s4)

Contrast with:

...
fpath = s1 + s2 + s3 + s4

Related

Note

Per iBug's response, this behavior does show up in the docs (https://docs.python.org/3/library/pathlib.html#basic-use) though I missed it in my searches.

Upvotes: 0

Views: 217

Answers (1)

iBug
iBug

Reputation: 37307

Most likely to your surprise, pathlib.Path does implement a __truediv__ method, which correspond to the / operator, and works exactly like what you'd expect from an __add__ method.

This sentence gives you an instant for your astonishment. You can now move on to the code:

s1 = 'components'
s2 = 'arms'
s3 = 'bones'
s4 = 'humerus'

fpath = Path(s1) / s2 / s3 / s4
# PosixPath('components/arms/bones/humerus')

It's actually documented.

Upvotes: 3

Related Questions