0

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.

PetMetz
  • 75
  • 1
  • 7
  • Using `+` for that would have been way too confusing - does `Path('a') + 'b'` give `Path('ab')` or `Path('a/b')`? – user2357112 Mar 17 '21 at 16:35

1 Answers1

3

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.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • Thanks-- that is in fact the behavior I alluded to. The PEP has this to say about the div operator: "The division operator came out first in a poll [10] about the path joining operator. Initial versions of pathlib [1] used square brackets (i.e. __getitem__) instead." I guess it's easy to see how I overlooked it. – PetMetz Mar 17 '21 at 16:24