Skip to content

Commit 8d0f369

Browse files
bpo-38811: Check for presence of os.link method in pathlib (GH-17225)
Commit 6b5b013 ("bpo-26978: Implement pathlib.Path.link_to (Using os.link) (GH-12990)") introduced a new link_to method in pathlib. However, this makes pathlib crash when the 'os' module is missing a 'link' method. Fix this by checking for the presence of the 'link' method on pathlib module import, and if it's not present, turn it into a runtime error like those emitted when there is no lchmod() or symlink(). Signed-off-by: Toke Høiland-Jørgensen <[email protected]> (cherry picked from commit 092435e) Co-authored-by: Toke Høiland-Jørgensen <[email protected]>
1 parent cd968de commit 8d0f369

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

Lib/pathlib.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -418,7 +418,12 @@ def lchmod(self, pathobj, mode):
418418

419419
unlink = os.unlink
420420

421-
link_to = os.link
421+
if hasattr(os, "link"):
422+
link_to = os.link
423+
else:
424+
@staticmethod
425+
def link_to(self, target):
426+
raise NotImplementedError("os.link() not available on this system")
422427

423428
rmdir = os.rmdir
424429

Lib/test/test_pathlib.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1672,6 +1672,7 @@ def test_rmdir(self):
16721672
self.assertFileNotFound(p.stat)
16731673
self.assertFileNotFound(p.unlink)
16741674

1675+
@unittest.skipUnless(hasattr(os, "link"), "os.link() is not present")
16751676
def test_link_to(self):
16761677
P = self.cls(BASE)
16771678
p = P / 'fileA'
@@ -1691,6 +1692,15 @@ def test_link_to(self):
16911692
self.assertEqual(os.stat(r).st_size, size)
16921693
self.assertTrue(q.stat)
16931694

1695+
@unittest.skipIf(hasattr(os, "link"), "os.link() is present")
1696+
def test_link_to_not_implemented(self):
1697+
P = self.cls(BASE)
1698+
p = P / 'fileA'
1699+
# linking to another path.
1700+
q = P / 'dirA' / 'fileAA'
1701+
with self.assertRaises(NotImplementedError):
1702+
p.link_to(q)
1703+
16941704
def test_rename(self):
16951705
P = self.cls(BASE)
16961706
p = P / 'fileA'
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix an unhandled exception in :mod:`pathlib` when :meth:`os.link` is missing. Patch by Toke Høiland-Jørgensen.

0 commit comments

Comments
 (0)