Skip to content

Commit 0f47a31

Browse files
authored
pathlib ABCs: support initializing paths with no arguments (#126608)
In the past I've equivocated about whether to require at least one argument in the `PurePathBase` (and `PathBase`) initializer, and what the default should be if we make it optional. I now have a local use case that has persuaded me to make it optional and default to the empty string (a `zipp.Path`-like class that treats relative and absolute paths similarly.) Happily this brings the base class more in line with `PurePath` and `Path`.
1 parent 6293d00 commit 0f47a31

File tree

2 files changed

+8
-9
lines changed

2 files changed

+8
-9
lines changed

Lib/pathlib/_abc.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -124,14 +124,12 @@ class PurePathBase:
124124
parser = ParserBase()
125125
_globber = PathGlobber
126126

127-
def __init__(self, arg, *args):
128-
paths = [arg]
129-
paths.extend(args)
130-
for path in paths:
131-
if not isinstance(path, str):
127+
def __init__(self, *args):
128+
for arg in args:
129+
if not isinstance(arg, str):
132130
raise TypeError(
133-
f"path should be a str, not {type(path).__name__!r}")
134-
self._raw_paths = paths
131+
f"argument should be a str, not {type(arg).__name__!r}")
132+
self._raw_paths = list(args)
135133
self._resolving = False
136134

137135
def with_segments(self, *pathsegments):
@@ -270,7 +268,7 @@ def relative_to(self, other, *, walk_up=False):
270268
raise ValueError(f"'..' segment in {str(other)!r} cannot be walked")
271269
else:
272270
parts0.append('..')
273-
return self.with_segments('', *reversed(parts0))
271+
return self.with_segments(*reversed(parts0))
274272

275273
def is_relative_to(self, other):
276274
"""Return True if the path is relative to another path or False.
@@ -746,7 +744,7 @@ def cwd(cls):
746744
# enable users to replace the implementation of 'absolute()' in a
747745
# subclass and benefit from the new behaviour here. This works because
748746
# os.path.abspath('.') == os.getcwd().
749-
return cls('').absolute()
747+
return cls().absolute()
750748

751749
def expanduser(self):
752750
""" Return a new path with expanded ~ and ~user constructs

Lib/test/test_pathlib/test_pathlib_abc.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@ def test_constructor_common(self):
148148
P = self.cls
149149
p = P('a')
150150
self.assertIsInstance(p, P)
151+
P()
151152
P('a', 'b', 'c')
152153
P('/a', 'b', 'c')
153154
P('a/b/c')

0 commit comments

Comments
 (0)