[Python-checkins] bpo-38878: Fix os.PathLike __subclasshook__ (GH-17336)

Ivan Levkivskyi webhook-mailer at python.org
Sun Dec 22 04:57:58 EST 2019


https://github.com/python/cpython/commit/eae87e3e4e0cb9a0ce10c2e101acb6995d79e09c
commit: eae87e3e4e0cb9a0ce10c2e101acb6995d79e09c
branch: master
author: Bar Harel <bzvi7919 at gmail.com>
committer: Ivan Levkivskyi <levkivskyi at gmail.com>
date: 2019-12-22T09:57:27Z
summary:

bpo-38878: Fix os.PathLike __subclasshook__ (GH-17336)

Quick subclasshook fix using the same method is being used in collections.abc (up to a certain degree).

files:
A Misc/NEWS.d/next/Library/2019-11-22-12-08-52.bpo-38878.EJ0cFf.rst
M Lib/os.py
M Lib/test/test_os.py

diff --git a/Lib/os.py b/Lib/os.py
index c901bd1b8ed9d..ca418edbc5736 100644
--- a/Lib/os.py
+++ b/Lib/os.py
@@ -26,6 +26,8 @@
 import sys
 import stat as st
 
+from _collections_abc import _check_methods
+
 _names = sys.builtin_module_names
 
 # Note:  more names are added to __all__ later.
@@ -1070,7 +1072,9 @@ def __fspath__(self):
 
     @classmethod
     def __subclasshook__(cls, subclass):
-        return hasattr(subclass, '__fspath__')
+        if cls is PathLike:
+            return _check_methods(subclass, '__fspath__')
+        return NotImplemented
 
     def __class_getitem__(cls, type):
         return cls
diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py
index f44ddbad7d641..82c441c204835 100644
--- a/Lib/test/test_os.py
+++ b/Lib/test/test_os.py
@@ -4048,6 +4048,14 @@ def test_bad_pathlike(self):
         self.assertRaises(ZeroDivisionError, self.fspath,
                           FakePath(ZeroDivisionError()))
 
+    def test_pathlike_subclasshook(self):
+        # bpo-38878: subclasshook causes subclass checks
+        # true on abstract implementation.
+        class A(os.PathLike):
+            pass
+        self.assertFalse(issubclass(FakePath, A))
+        self.assertTrue(issubclass(FakePath, os.PathLike))
+
     def test_pathlike_class_getitem(self):
         self.assertIs(os.PathLike[bytes], os.PathLike)
 
diff --git a/Misc/NEWS.d/next/Library/2019-11-22-12-08-52.bpo-38878.EJ0cFf.rst b/Misc/NEWS.d/next/Library/2019-11-22-12-08-52.bpo-38878.EJ0cFf.rst
new file mode 100644
index 0000000000000..9cbdf08dd53e3
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2019-11-22-12-08-52.bpo-38878.EJ0cFf.rst
@@ -0,0 +1,2 @@
+Fixed __subclasshook__ of :class:`os.PathLike` to return a correct result
+upon inheritence. Patch by Bar Harel.



More information about the Python-checkins mailing list