Search code examples
pythonpython-3.xpathlib

python pathlib operator '/' - how does it do it?


I found the pathlib syntax - or is it the Python syntax - surprising. I'd like to know how this makes the forward slash / act as a joiner of WindowsPaths etc. Does it override/overload / ? It seems to be in a magical context, the slash is between a WindowsPath type object and a string. If I try between 2 strings it fails to join the 2 strings (e.g. "123" / "123" fails)

p=pathlib.Path(".")

p
Out[66]: WindowsPath('.')

p.cwd()
Out[67]: WindowsPath('C:/Users/user1')

p.cwd() / "mydir"
Out[68]: WindowsPath('C:/Users/user1/mydir')

Solution

  • The Path class has a __truediv__ method that returns another Path. You can do the same with your own classes:

    >>> class WeirdThing(object):
            def __truediv__(self, other):
                return 'Division!'
    
    >>> WeirdThing() / WeirdThing()
    'Division!'