mirror of
https://github.com/python/cpython.git
synced 2025-11-03 03:22:27 +00:00
GH-100479: Add pathlib.PurePath.with_segments() (GH-103975)
Add `pathlib.PurePath.with_segments()`, which creates a path object from arguments. This method is called whenever a derivative path is created, such as from `pathlib.PurePath.parent`. Subclasses may override this method to share information between path objects. Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
This commit is contained in:
parent
1afe0e0320
commit
d00d942149
5 changed files with 108 additions and 47 deletions
|
|
@ -530,10 +530,10 @@ Pure paths provide the following methods and properties:
|
|||
unintended effects.
|
||||
|
||||
|
||||
.. method:: PurePath.joinpath(*other)
|
||||
.. method:: PurePath.joinpath(*pathsegments)
|
||||
|
||||
Calling this method is equivalent to combining the path with each of
|
||||
the *other* arguments in turn::
|
||||
the given *pathsegments* in turn::
|
||||
|
||||
>>> PurePosixPath('/etc').joinpath('passwd')
|
||||
PurePosixPath('/etc/passwd')
|
||||
|
|
@ -680,6 +680,30 @@ Pure paths provide the following methods and properties:
|
|||
PureWindowsPath('README')
|
||||
|
||||
|
||||
.. method:: PurePath.with_segments(*pathsegments)
|
||||
|
||||
Create a new path object of the same type by combining the given
|
||||
*pathsegments*. This method is called whenever a derivative path is created,
|
||||
such as from :attr:`parent` and :meth:`relative_to`. Subclasses may
|
||||
override this method to pass information to derivative paths, for example::
|
||||
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
class MyPath(PurePosixPath):
|
||||
def __init__(self, *pathsegments, session_id):
|
||||
super().__init__(*pathsegments)
|
||||
self.session_id = session_id
|
||||
|
||||
def with_segments(self, *pathsegments):
|
||||
return type(self)(*pathsegments, session_id=self.session_id)
|
||||
|
||||
etc = MyPath('/etc', session_id=42)
|
||||
hosts = etc / 'hosts'
|
||||
print(hosts.session_id) # 42
|
||||
|
||||
.. versionadded:: 3.12
|
||||
|
||||
|
||||
.. _concrete-paths:
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -348,6 +348,11 @@ inspect
|
|||
pathlib
|
||||
-------
|
||||
|
||||
* Add support for subclassing :class:`pathlib.PurePath` and
|
||||
:class:`~pathlib.Path`, plus their Posix- and Windows-specific variants.
|
||||
Subclasses may override the :meth:`~pathlib.PurePath.with_segments` method
|
||||
to pass information between path instances.
|
||||
|
||||
* Add :meth:`~pathlib.Path.walk` for walking the directory trees and generating
|
||||
all file or directory names within them, similar to :func:`os.walk`.
|
||||
(Contributed by Stanislav Zmiev in :gh:`90385`.)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue