Skip to content

Commit bb45530

Browse files
scivisiondpgeorge
authored andcommitted
pathlib: Add Path.expanduser().
The behaviour follows CPython. Signed-off-by: Michael Hirsch <michael@scivision.dev> Signed-off-by: Damien George <damien@micropython.org>
1 parent 5dad29e commit bb45530

3 files changed

Lines changed: 16 additions & 1 deletion

File tree

python-stdlib/pathlib/manifest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
metadata(version="0.0.2")
1+
metadata(version="0.1.0")
22

33
module("pathlib.py")

python-stdlib/pathlib/pathlib.py

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

190+
def expanduser(self):
191+
if self._path == "~" or self._path.startswith("~" + _SEP):
192+
return Path(os.getenv("HOME") + self._path[1:])
193+
if self._path[0] == "~":
194+
raise RuntimeError("user expansion not supported")
195+
return self
196+
190197
@property
191198
def stem(self):
192199
return self.name.rsplit(".", 1)[0]

python-stdlib/pathlib/tests/test_pathlib.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,3 +339,11 @@ def test_rtruediv_inplace(self):
339339
res = "foo"
340340
res /= Path("bar")
341341
self.assertTrue(res == Path("foo/bar"))
342+
343+
def test_expanduser(self):
344+
self.assertFalse(str(Path("~").expanduser()) == "~")
345+
self.assertTrue(str(Path("~").expanduser()) == os.getenv("HOME"))
346+
self.assertTrue(str(Path("~/foo").expanduser()) == os.getenv("HOME") + "/foo")
347+
348+
with self.assertRaises(RuntimeError):
349+
Path("~foo").expanduser()

0 commit comments

Comments
 (0)