Question

I would like to implement the concatenation of paths to files using "\" as an operator, redefining the corresponding function (if any).

For example:

path1 = '\home'
path2 = 'codes'

codepath = path1 \ path2

Thus, adding str "\" between path1 and path2 in the redefition of the method, I should assert codepath = '\home\codes'

Was it helpful?

Solution

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")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top