-2

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

1 Answers1

1

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

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • So basically this changes the original functionality of __truediv()__ method? – Lucca Marques Aug 26 '20 at 23:04
  • 1
    I just saw your comment @LuccaLemeMarques. There's no _original_ functionality. You give it that functionality (the ability to participate in an expression of the form `a / b`) by implementing the method. – Pranav Hosangadi Jun 25 '21 at 16:13