Skip to content

Commit

Permalink
pathlib: add Path.expanduser()
Browse files Browse the repository at this point in the history
Signed-off-by: Michael Hirsch <michael@scivision.dev>
  • Loading branch information
scivision committed Sep 14, 2023
1 parent e6b89ea commit ec34212
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
7 changes: 7 additions & 0 deletions python-stdlib/pathlib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,13 @@ def with_suffix(self, suffix):
index = -len(self.suffix) or None
return Path(self._path[:index] + suffix)

def expanduser(self):
if self._path == "~" or self._path.startswith("~/"):
return Path(os.getenv("HOME") + self._path[1:])
if self._path[0] == "~":
raise RuntimeError("User home directory expansion not supported.")
return self

@property
def stem(self):
return self.name.rsplit(".", 1)[0]
Expand Down
5 changes: 5 additions & 0 deletions python-stdlib/pathlib/tests/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,3 +322,8 @@ def test_with_suffix(self):
self.assertTrue(Path("foo/test").with_suffix(".tar") == Path("foo/test.tar"))
self.assertTrue(Path("foo/bar.bin").with_suffix(".txt") == Path("foo/bar.txt"))
self.assertTrue(Path("bar.txt").with_suffix("") == Path("bar"))

def test_expanduser(self):
self.assertFalse(Path("~") == "~")
self.assertTrue(Path("~").expanduser() == os.getenv("HOME"))
self.assertTrue(Path("~/foo").expanduser() == os.getenv("HOME") + "/foo")

0 comments on commit ec34212

Please sign in to comment.