Skip to content

Commit 092435e

Browse files
tohojovstinner
authored andcommitted
bpo-38811: Check for presence of os.link method in pathlib (pythonGH-17225)
Commit 6b5b013 ("bpo-26978: Implement pathlib.Path.link_to (Using os.link) (pythonGH-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 <toke@redhat.com>
1 parent 1ca8fb1 commit 092435e

3 files changed

Lines changed: 17 additions & 1 deletion

File tree

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
@@ -1759,6 +1759,7 @@ def test_rmdir(self):
17591759
self.assertFileNotFound(p.stat)
17601760
self.assertFileNotFound(p.unlink)
17611761

1762+
@unittest.skipUnless(hasattr(os, "link"), "os.link() is not present")
17621763
def test_link_to(self):
17631764
P = self.cls(BASE)
17641765
p = P / 'fileA'
@@ -1778,6 +1779,15 @@ def test_link_to(self):
17781779
self.assertEqual(os.stat(r).st_size, size)
17791780
self.assertTrue(q.stat)
17801781

1782+
@unittest.skipIf(hasattr(os, "link"), "os.link() is present")
1783+
def test_link_to_not_implemented(self):
1784+
P = self.cls(BASE)
1785+
p = P / 'fileA'
1786+
# linking to another path.
1787+
q = P / 'dirA' / 'fileAA'
1788+
with self.assertRaises(NotImplementedError):
1789+
p.link_to(q)
1790+
17811791
def test_rename(self):
17821792
P = self.cls(BASE)
17831793
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)