10000 gh-124825: Adding PurePath.erase_parents() to pathlib by dlenski · Pull Request #135406 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-124825: Adding PurePath.erase_parents() to pathlib #135406

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,27 @@ def with_segments(self, *pathsegments):
are created from methods like `iterdir()`.
"""
return type(self)(*pathsegments)

def erase_parents(self):
r"""
Remove path components referring to parent directories ('..'),
without any attempt to verify the existence or structure of any
path components.

If this is a relative path, there may be leftover '..' segments
after erasing parent segments. For example:

- Path('spam/../../eggs').erase_parents() == Path('../eggs')

If this is an absolute path, and it reaches the root filesystem
(or the root of a drive or UNC share for Windows paths),
further '..' components will be ignored. For example:

- Path('/spam/../../../eggs').erase_parents() == Path('/eggs')
- PureWindowsPath(r'c:\spam\..\..\eggs').erase_parents() == PureWindowsPath(r'c:\eggs')
- PureWindowsPath(r'\\server\share\foo\..\..\eggs').erase_parents() == PureWindowsPath(r'\\server\share\eggs')
"""
return type(self)(self._flavour.normpath(self))

@classmethod
def _parse_path(cls, path):
Expand Down Expand Up @@ -479,7 +500,7 @@ def as_uri(self):
# It's a posix path => 'file:///etc/hosts'
prefix = 'file://'
path = str(self)
return prefix + urlquote_from_bytes(os.fsencode(path))
return prefix + urlquote_from_bytes(os.fsencode(path))

@property
def _str_normcase(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added :func:`pathlib.PurePath.erase_parents`, which will remove path components referring to parent directories ('..') without any attempt to verify the existence or structure of any path components.
Loading
0