Skip to content

Commit 0eba105

Browse files
committed
pathlib: add Path.expanduser()
Signed-off-by: Michael Hirsch <michael@scivision.dev>
1 parent e6b89ea commit 0eba105

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

python-stdlib/pathlib/pathlib.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,13 @@ def with_suffix(self, suffix):
184184
index = -len(self.suffix) or None
185185
return Path(self._path[:index] + suffix)
186186

187+
def expanduser(self):
188+
if self._path == "~" or self._path.startswith("~/"):
189+
return os.getenv("HOME") + self._path[1:]
190+
if self._path[0] == "~":
191+
raise RuntimeError("User home directory expansion not supported.")
192+
return self._path
193+
187194
@property
188195
def stem(self):
189196
return self.name.rsplit(".", 1)[0]

python-stdlib/pathlib/tests/test_pathlib.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,3 +322,8 @@ def test_with_suffix(self):
322322
self.assertTrue(Path("foo/test").with_suffix(".tar") == Path("foo/test.tar"))
323323
self.assertTrue(Path("foo/bar.bin").with_suffix(".txt") == Path("foo/bar.txt"))
324324
self.assertTrue(Path("bar.txt").with_suffix("") == Path("bar"))
325+
326+
def test_expanduser(self):
327+
self.assertFalse(Path("~") == "~")
328+
self.assertTrue(Path("~").expanduser() == os.getenv("HOME"))
329+
self.assertTrue(Path("~/foo").expanduser() == os.getenv("HOME") + "/foo")

0 commit comments

Comments
 (0)