diff --git a/python-stdlib/pathlib/pathlib.py b/python-stdlib/pathlib/pathlib.py index e0f961373..6cd5c37f2 100644 --- a/python-stdlib/pathlib/pathlib.py +++ b/python-stdlib/pathlib/pathlib.py @@ -187,6 +187,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("~" + _SEP): + 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] diff --git a/python-stdlib/pathlib/tests/test_pathlib.py b/python-stdlib/pathlib/tests/test_pathlib.py index e632e1242..889ef306a 100644 --- a/python-stdlib/pathlib/tests/test_pathlib.py +++ b/python-stdlib/pathlib/tests/test_pathlib.py @@ -323,6 +323,14 @@ def test_with_suffix(self): 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(str(Path("~").expanduser()) == "~") + self.assertTrue(str(Path("~").expanduser()) == os.getenv("HOME")) + self.assertTrue(str(Path("~/foo").expanduser()) == os.getenv("HOME") + "/foo") + + with self.assertRaises(RuntimeError): + Path("~foo").expanduser() + def test_rtruediv(self): """Works as of micropython ea7031f""" res = "foo" / Path("bar")