The pathlib
module supports /
for concatenating path objects.
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')
As an example of how to use __div__
, here's a simple class that extends str
. It should work as long as at least one argument is an instance of MyPath
(i.e., it won't work with two plain strings).
class MyPath(str):
def __div__(self, other):
assert isinstance(other, str)
return os.path.join(self, other)
def __rdiv__(self, other):
assert isinstance(other, str)
return os.path.join(other, self)
# Using __div__
print MyPath("/home/bob") / MyPath("bin")
print MyPath("/home/bob") / "bin"
# Using __rdiv__
print "/home/bob" / MyPath("bin")