Skip to content

Commit 2f45658

Browse files
committed
Issue #22570: Add 'path' attribute to pathlib.Path objects.
1 parent 56990a7 commit 2f45658

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

Lib/pathlib.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,13 @@ def __str__(self):
645645
self._parts) or '.'
646646
return self._str
647647

648+
@property
649+
def path(self):
650+
try:
651+
return self._str
652+
except AttributeError:
653+
return str(self)
654+
648655
def as_posix(self):
649656
"""Return the string representation of the path with forward (/)
650657
slashes."""

Lib/test/test_pathlib.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,22 @@ def test_name_common(self):
480480
self.assertEqual(P('a/b.py').name, 'b.py')
481481
self.assertEqual(P('/a/b.py').name, 'b.py')
482482

483+
def test_path_common(self):
484+
P = self.cls
485+
def check(arg, expected=None):
486+
if expected is None:
487+
expected = arg
488+
self.assertEqual(P(arg).path, expected.replace('/', self.sep))
489+
check('', '.')
490+
check('.')
491+
check('/')
492+
check('a/b')
493+
check('/a/b')
494+
check('/a/b/', '/a/b')
495+
check('/a/b/.', '/a/b')
496+
check('a/b.py')
497+
check('/a/b.py')
498+
483499
def test_suffix_common(self):
484500
P = self.cls
485501
self.assertEqual(P('').suffix, '')
@@ -903,6 +919,17 @@ def test_name(self):
903919
self.assertEqual(P('//My.py/Share.php').name, '')
904920
self.assertEqual(P('//My.py/Share.php/a/b').name, 'b')
905921

922+
def test_path(self):
923+
P = self.cls
924+
self.assertEqual(P('c:').path, 'c:')
925+
self.assertEqual(P('c:/').path, 'c:\\')
926+
self.assertEqual(P('c:a/b').path, 'c:a\\b')
927+
self.assertEqual(P('c:/a/b').path, 'c:\\a\\b')
928+
self.assertEqual(P('c:a/b.py').path, 'c:a\\b.py')
929+
self.assertEqual(P('c:/a/b.py').path, 'c:\\a\\b.py')
930+
self.assertEqual(P('//My.py/Share.php').path, '\\\\My.py\\Share.php\\')
931+
self.assertEqual(P('//My.py/Share.php/a/b').path, '\\\\My.py\\Share.php\\a\\b')
932+
906933
def test_suffix(self):
907934
P = self.cls
908935
self.assertEqual(P('c:').suffix, '')

Misc/NEWS

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ Core and Builtins
1313
Library
1414
-------
1515

16+
- Issue #22570: Add 'path' attribute to pathlib.Path objects,
17+
returning the same as str(), to make it more similar to DirEntry.
18+
Library code can now write getattr(p, 'path', p) to get the path as
19+
a string from a Path, a DirEntry, or a plain string. This is
20+
essentially a small one-off protocol.
21+
1622
- Issue #26012: Don't traverse into symlinks for ** pattern in
1723
pathlib.Path.[r]glob().
1824

0 commit comments

Comments
 (0)