Search code examples
pythonpathlib

How does PathLib Works


I was using Pathlib on Python3.x and I found a piece of code that got me curious.

from pathlib import Path
BASE = Path('/mydir').resolve(strict=True).parent.parent
print( BASE / 'Sub-dir')

And that works perfectly, printing out:

/mydir/Sub-dir

I got curious to understand how that works, if someone could help me out. Regards


Solution

  • It implements the __truediv()__ method.

    From https://github.com/python/cpython/blob/master/Lib/pathlib.py

    def __truediv__(self, key):
        try:
            return self._make_child((key,))
        except TypeError:
            return NotImplemented
    

    __truediv()__ defines how the division operator / works with objects of the class. In this case, it makes a child path with the second operand