0

I'm trying to traverse up the directory tree like this:

from pathlib import Path
# ...
        curr = Path(os.getcwd())
        while True:
            # do something with curr
            if curr is curr.anchor:
                break
            curr = curr.parent

To my surprise, even though str(curr) == str(curr.anchor), both the expressions curr is curr.anchor and curr == curr.anchor return False, so I get an infinite loop.

Is the right way to fix this really changing the condition as follows:

            if str(curr) == str(curr.anchor):
                break

I'm curious to know why the pathlib.Path equality operator works this way, but I'm also open to more Pythonic solutions to the main problem.

tomocafe
  • 1,425
  • 4
  • 20
  • 35
  • 1
    `is` is [the wrong approach](https://stackoverflow.com/questions/1504717/why-does-comparing-strings-using-either-or-is-sometimes-produce-a-differe) for sure. What happens if you print the `repr` of these equal-but-not-equal paths? – Thomas Oct 11 '22 at 18:20

1 Answers1

2

curr is a Path. curr.anchor is a string. A string and a Path will not be equal, and will certainly not be the same object.

user2357112
  • 260,549
  • 28
  • 431
  • 505