Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
a6fdd0e
Add `pathlib.PurePath.makepath()`; unify path object construction
barneygale Nov 20, 2022
b061747
Fix reST role name.
barneygale Dec 24, 2022
99eb8b1
Move call to `os.getcwd()` back into `Path.cwd()`
barneygale Dec 24, 2022
4759d01
Merge branch 'main' into gh-100479-add-makepath
barneygale Jan 5, 2023
ef6f4c3
Merge branch 'main' into gh-100479-add-makepath
barneygale Apr 3, 2023
595b8ae
Add news blurb.
barneygale Apr 3, 2023
dcfe70a
Merge branch 'main' into gh-100479-add-makepath
barneygale Apr 9, 2023
117fe4b
Add whatsnew entry
barneygale Apr 10, 2023
e75dedc
Merge branch 'main' into gh-100479-add-makepath
barneygale Apr 12, 2023
5a6bd3f
Merge branch 'main' into gh-100479-add-makepath
barneygale Apr 13, 2023
f2f1048
other --> pathsegments
barneygale Apr 24, 2023
3c172fb
Update Lib/pathlib.py
barneygale Apr 24, 2023
4637109
joinpath(*args) --> joinpath(*pathsegments)
barneygale Apr 24, 2023
ae48454
Restore _PathParents
barneygale Apr 25, 2023
e7a8fe3
Add note to `parents` about potential reference cycle.
barneygale Apr 25, 2023
7f12faa
Replace `makepath()` method with `template` initialiser argument.
barneygale Apr 25, 2023
687c764
Apply suggestions from code review
barneygale Apr 25, 2023
d7e326a
Fix docs for other classes.
barneygale Apr 25, 2023
a65d499
Pass template to `super()` to support diamond inheritance.
barneygale Apr 26, 2023
d4b15d7
Fixed missed `template` argument to super().
barneygale Apr 26, 2023
958b183
template --> blueprint
barneygale Apr 27, 2023
1e10188
Merge branch 'main' into gh-100479-add-makepath
barneygale May 2, 2023
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
Prev Previous commit
Next Next commit
template --> blueprint
  • Loading branch information
barneygale committed Apr 27, 2023
commit 958b183feaa334a1575e7e91e8f6106eb843e6f7
36 changes: 18 additions & 18 deletions Doc/library/pathlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ Pure path objects provide path-handling operations which don't actually
access a filesystem. There are three ways to access these classes, which
we also call *flavours*:

.. class:: PurePath(*pathsegments, template=None)
.. class:: PurePath(*pathsegments, blueprint=None)

A generic class that represents the system's path flavour (instantiating
it creates either a :class:`PurePosixPath` or a :class:`PureWindowsPath`)::
Expand Down Expand Up @@ -150,18 +150,18 @@ we also call *flavours*:
to ``PurePosixPath('bar')``, which is wrong if ``foo`` is a symbolic link
to another directory)

The optional *template* argument may provide another path object. It is
The optional *blueprint* argument may provide another path object. It is
supplied whenever a new path object is created from an existing one, such
as in :attr:`parent` or :meth:`relative_to`. Subclasses may use this to
pass information between path objects. For example::

from pathlib import PurePosixPath

class MyPath(PurePosixPath):
def __init__(self, *pathsegments, template=None, session_id=None):
super().__init__(*pathsegments, template=template)
if template:
self.session_id = template.session_id
def __init__(self, *pathsegments, blueprint=None, session_id=None):
super().__init__(*pathsegments, blueprint=blueprint)
if blueprint:
self.session_id = blueprint.session_id
else:
self.session_id = session_id

Expand All @@ -170,29 +170,29 @@ we also call *flavours*:
print(hosts.session_id) # 42

.. note::
The classes provided in this module ignore the *template* argument.
The classes provided in this module ignore the *blueprint* argument.
It is there purely as a hook for user-defined subclasses.

.. versionadded:: 3.12
The *template* argument.
The *blueprint* argument.

Pure path objects implement the :class:`os.PathLike` interface, allowing them
to be used anywhere the interface is accepted.

.. versionchanged:: 3.6
Added support for the :class:`os.PathLike` interface.

.. class:: PurePosixPath(*pathsegments, template=None)
.. class:: PurePosixPath(*pathsegments, blueprint=None)

A subclass of :class:`PurePath`, this path flavour represents non-Windows
filesystem paths::

>>> PurePosixPath('/etc')
PurePosixPath('/etc')

*pathsegments* and *template* are specified similarly to :class:`PurePath`.
*pathsegments* and *blueprint* are specified similarly to :class:`PurePath`.

.. class:: PureWindowsPath(*pathsegments, template=None)
.. class:: PureWindowsPath(*pathsegments, blueprint=None)

A subclass of :class:`PurePath`, this path flavour represents Windows
filesystem paths, including `UNC paths`_::
Expand All @@ -202,7 +202,7 @@ we also call *flavours*:
>>> PureWindowsPath('//server/share/file')
PureWindowsPath('//server/share/file')

*pathsegments* and *template* are specified similarly to :class:`PurePath`.
*pathsegments* and *blueprint* are specified similarly to :class:`PurePath`.

.. _unc paths: https://en.wikipedia.org/wiki/Path_(computing)#UNC

Expand Down Expand Up @@ -716,7 +716,7 @@ Concrete paths are subclasses of the pure path classes. In addition to
operations provided by the latter, they also provide methods to do system
calls on path objects. There are three ways to instantiate concrete paths:

.. class:: Path(*pathsegments, template=None)
.. class:: Path(*pathsegments, blueprint=None)

A subclass of :class:`PurePath`, this class represents concrete paths of
the system's path flavour (instantiating it creates either a
Expand All @@ -725,27 +725,27 @@ calls on path objects. There are three ways to instantiate concrete paths:
>>> Path('setup.py')
PosixPath('setup.py')

*pathsegments* and *template* are specified similarly to :class:`PurePath`.
*pathsegments* and *blueprint* are specified similarly to :class:`PurePath`.

.. class:: PosixPath(*pathsegments, template=None)
.. class:: PosixPath(*pathsegments, blueprint=None)

A subclass of :class:`Path` and :class:`PurePosixPath`, this class
represents concrete non-Windows filesystem paths::

>>> PosixPath('/etc')
PosixPath('/etc')

*pathsegments* and *template* are specified similarly to :class:`PurePath`.
*pathsegments* and *blueprint* are specified similarly to :class:`PurePath`.

.. class:: WindowsPath(*pathsegments, template=None)
.. class:: WindowsPath(*pathsegments, blueprint=None)

A subclass of :class:`Path` and :class:`PureWindowsPath`, this class
represents concrete Windows filesystem paths::

>>> WindowsPath('c:/Program Files/')
WindowsPath('c:/Program Files')

*pathsegments* and *template* are specified similarly to :class:`PurePath`.
*pathsegments* and *blueprint* are specified similarly to :class:`PurePath`.

You can only instantiate the class flavour that corresponds to your system
(allowing system calls on non-compatible path flavours could lead to
Expand Down
34 changes: 17 additions & 17 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ def __reduce__(self):
# when pickling related paths.
return (self.__class__, self.parts)

def __init__(self, *args, template=None):
def __init__(self, *args, blueprint=None):
if not args:
path = ''
elif len(args) == 1:
Expand Down Expand Up @@ -335,7 +335,7 @@ def _load_parts(self):

def _from_parsed_parts(self, drv, root, tail):
path_str = self._format_parsed_parts(drv, root, tail)
path = type(self)(path_str, template=self)
path = type(self)(path_str, blueprint=self)
path._str = path_str or '.'
path._drv = drv
path._root = root
Expand Down Expand Up @@ -575,7 +575,7 @@ def relative_to(self, other, /, *_deprecated, walk_up=False):
warnings._deprecated("pathlib.PurePath.relative_to(*args)", msg,
remove=(3, 14))
path_cls = type(self)
other = path_cls(other, *_deprecated, template=self)
other = path_cls(other, *_deprecated, blueprint=self)
for step, path in enumerate([other] + list(other.parents)):
if self.is_relative_to(path):
break
Expand All @@ -584,7 +584,7 @@ def relative_to(self, other, /, *_deprecated, walk_up=False):
if step and not walk_up:
raise ValueError(f"{str(self)!r} is not in the subpath of {str(other)!r}")
parts = ['..'] * step + self._tail[len(path._tail):]
return path_cls(*parts, template=self)
return path_cls(*parts, blueprint=self)

def is_relative_to(self, other, /, *_deprecated):
"""Return True if the path is relative to another path or False.
Expand All @@ -595,7 +595,7 @@ def is_relative_to(self, other, /, *_deprecated):
"scheduled for removal in Python {remove}")
warnings._deprecated("pathlib.PurePath.is_relative_to(*args)",
msg, remove=(3, 14))
other = type(self)(other, *_deprecated, template=self)
other = type(self)(other, *_deprecated, blueprint=self)
return other == self or other in self.parents

@property
Expand All @@ -613,7 +613,7 @@ def joinpath(self, *pathsegments):
paths) or a totally different path (if one of the arguments is
anchored).
"""
return type(self)(self._raw_path, *pathsegments, template=self)
return type(self)(self._raw_path, *pathsegments, blueprint=self)

def __truediv__(self, key):
try:
Expand All @@ -623,7 +623,7 @@ def __truediv__(self, key):

def __rtruediv__(self, key):
try:
return type(self)(key, self._raw_path, template=self)
return type(self)(key, self._raw_path, blueprint=self)
except TypeError:
return NotImplemented

Expand Down Expand Up @@ -672,7 +672,7 @@ def match(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
pat = type(self)(path_pattern, template=self)
pat = type(self)(path_pattern, blueprint=self)
if not pat.parts:
raise ValueError("empty pattern")
pat_parts = pat._parts_normcase
Expand Down Expand Up @@ -726,12 +726,12 @@ class Path(PurePath):
"""
__slots__ = ()

def __init__(self, *args, template=None, **kwargs):
def __init__(self, *args, blueprint=None, **kwargs):
if kwargs:
msg = ("support for supplying keyword arguments to pathlib.PurePath "
"is deprecated and scheduled for removal in Python {remove}")
warnings._deprecated("pathlib.PurePath(**kwargs)", msg, remove=(3, 14))
super().__init__(*args, template=template)
super().__init__(*args, blueprint=blueprint)

def __new__(cls, *args, **kwargs):
if cls is Path:
Expand All @@ -747,7 +747,7 @@ def _make_child_relpath(self, name):
path_str = f'{path_str}{name}'
else:
path_str = name
path = type(self)(path_str, template=self)
path = type(self)(path_str, blueprint=self)
path._str = path_str
path._drv = self.drive
path._root = self.root
Expand Down Expand Up @@ -797,7 +797,7 @@ def samefile(self, other_path):
try:
other_st = other_path.stat()
except AttributeError:
other_st = type(self)(other_path, template=self).stat()
other_st = type(self)(other_path, blueprint=self).stat()
return self._flavour.samestat(st, other_st)

def iterdir(self):
Expand Down Expand Up @@ -859,7 +859,7 @@ def absolute(self):
cwd = self._flavour.abspath(self.drive)
else:
cwd = os.getcwd()
return type(self)(cwd, self._raw_path, template=self)
return type(self)(cwd, self._raw_path, blueprint=self)

def resolve(self, strict=False):
"""
Expand All @@ -877,7 +877,7 @@ def check_eloop(e):
except OSError as e:
check_eloop(e)
raise
p = type(self)(s, template=self)
p = type(self)(s, blueprint=self)

# In non-strict mode, realpath() doesn't raise on symlink loops.
# Ensure we get an exception by calling stat()
Expand Down Expand Up @@ -967,7 +967,7 @@ def readlink(self):
"""
if not hasattr(os, "readlink"):
raise NotImplementedError("os.readlink() not available on this system")
return type(self)(os.readlink(self), template=self)
return type(self)(os.readlink(self), blueprint=self)

def touch(self, mode=0o666, exist_ok=True):
"""
Expand Down Expand Up @@ -1056,7 +1056,7 @@ def rename(self, target):
Returns the new Path instance pointing to the target path.
"""
os.rename(self, target)
return type(self)(target, template=self)
return type(self)(target, blueprint=self)

def replace(self, target):
"""
Expand All @@ -1069,7 +1069,7 @@ def replace(self, target):
Returns the new Path instance pointing to the target path.
"""
os.replace(self, target)
return type(self)(target, template=self)
return type(self)(target, blueprint=self)

def symlink_to(self, target, target_is_directory=False):
"""
Expand Down
18 changes: 9 additions & 9 deletions Lib/test/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@
#

class _BasePurePathSubclass(object):
def __init__(self, *args, template=None, session_id=None):
super().__init__(*args, template=template)
if template:
self.session_id = template.session_id
def __init__(self, *args, blueprint=None, session_id=None):
super().__init__(*args, blueprint=blueprint)
if blueprint:
self.session_id = blueprint.session_id
else:
self.session_id = session_id

Expand Down Expand Up @@ -122,11 +122,11 @@ def test_str_subclass_common(self):
self._check_str_subclass('a/b.txt')
self._check_str_subclass('/a/b.txt')

def test_template_common(self):
def test_blueprint_common(self):
class P(_BasePurePathSubclass, self.cls):
pass
p = P('foo', 'bar', session_id=42)
self.assertEqual(42, P(template=p).session_id)
self.assertEqual(42, P(blueprint=p).session_id)
self.assertEqual(42, (p / 'foo').session_id)
self.assertEqual(42, ('foo' / p).session_id)
self.assertEqual(42, p.joinpath('foo').session_id)
Expand Down Expand Up @@ -1625,14 +1625,14 @@ def test_home(self):
env['HOME'] = os.path.join(BASE, 'home')
self._test_home(self.cls.home())

def test_template(self):
def test_blueprint(self):
class P(_BasePurePathSubclass, self.cls):
pass
p = P(BASE, session_id=42)
self.assertEqual(42, P(template=p).session_id)
self.assertEqual(42, P(blueprint=p).session_id)
self.assertEqual(42, p.absolute().session_id)
self.assertEqual(42, p.resolve().session_id)
self.assertEqual(42, P('~', template=p).expanduser().session_id)
self.assertEqual(42, P('~', blueprint=p).expanduser().session_id)
self.assertEqual(42, (p / 'fileA').rename(p / 'fileB').session_id)
self.assertEqual(42, (p / 'fileB').replace(p / 'fileA').session_id)
if os_helper.can_symlink():
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Add optional *template* argument to :class:`pathlib.PurePath` and
Add optional *blueprint* argument to :class:`pathlib.PurePath` and
:class:`~pathlib.Path`. This argument is supplied whenever a derivative path
is created, such as from :attr:`pathlib.PurePath.parent`. Subclasses may use
to pass information to derivative paths. Patch by Barney Gale.