Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between slash operator and comma separator in pathlib Path

I read that in pathlib we can create a child path by using / between two paths, where a comma would also work. However, I can't find out if there is a difference between the two cases. In the following example, the output is the same:

from pathlib import Path

p = Path('/hello', 'world')
s = Path(p, 'how', 'are', 'you')
ns = Path(p / 'how', 'are', 'you')

print(s)
print(ns)

But considering that pathlib is heavily object-oriented, I guess there might be something different behind the scenes. Is there a difference between using / in Path in contrast with a comma?

like image 464
Bram Vanroy Avatar asked Feb 24 '18 19:02

Bram Vanroy


1 Answers

The whole point of using the / operator between pathlib.Path objects or a Path object with a str object is so you can avoid wrapping everything in calls to Path.

>>> from pathlib import Path
>>> p = Path('/hello', 'world')
>>> p / 'how'
PosixPath('/hello/world/how')
>>> p / 'how' / 'are' / 'you'
PosixPath('/hello/world/how/are/you')

The distinction isn't between using "a comma" and a /, it's between using / and the constructor, Path.

I suppose, / is supposed to be similar to joinpath:

>>> p.joinpath('how','are','you')
PosixPath('/hello/world/how/are/you')

But somewhere under the hood you are creating a new Path instance, so Path is called anyway.

Note, from the docs:

When several absolute paths are given, the last is taken as an anchor (mimicking os.path.join()’s behaviour):

So they both have this behavior as well:

>>> '/etc' / p / '/usr'
PosixPath('/usr')
>>> Path('/etc', p, '/usr')
PosixPath('/usr')
like image 89
juanpa.arrivillaga Avatar answered Oct 06 '22 07:10

juanpa.arrivillaga