New submission from Yaroslav <flower.m...@gmail.com>:

As I can see, pathlib path parents don't support slicing with negative indexes: 

>>> 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 slicing:

>>> path.parents[-1] == path.parents[parents_count]
True
>>> path.parents[-2] == path.parents[parents_count - 1]
True

So what do you guys think about this?

----------
components: Library (Lib)
messages: 375076
nosy: ypank
priority: normal
severity: normal
status: open
title: Pathlib parents doesn't support slicing with negative indexes
type: behavior
versions: Python 3.10, Python 3.5, Python 3.6, Python 3.7, Python 3.8, Python 
3.9

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue41511>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to