bpo-21041: Add negative indexing to pathlib path parents by ypankovych · Pull Request #21799 · python/cpython
As I can see, pathlib path parents don't support negative indexing:
>>> import pathlib >>> path = pathlib.PosixPath("some/very/long/path/here") >>> path.parents[-1] ... raise IndexError(idx) IndexError: -1
That's kinda weird for python. I mean, in regular list/etc if I need the last element, I'd normally do list[-1], but here to get the last parent, I need to actually know how many parents do I have.
So now, I can do something like this:
>>> parents_count = len(path.parents) - 1 >>> path.parents[parents_count] PosixPath('.')
So that's how I can get the last parent. But is it pythonic? No.
So, I decided to fix this, and now we can do negative indexing:
>>> path.parents[-1] == path.parents[parents_count] True >>> path.parents[-2] == path.parents[parents_count - 1] True