]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-45192: Fix a bug that infers the type of an os.PathLike[bytes] object as str...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Wed, 20 Oct 2021 21:25:10 +0000 (14:25 -0700)
committerGitHub <noreply@github.com>
Wed, 20 Oct 2021 21:25:10 +0000 (23:25 +0200)
An object implementing the os.PathLike protocol can represent a file
system path as a str or bytes object.
Therefore, _infer_return_type function should infer os.PathLike[str]
object as str type and os.PathLike[bytes] object as bytes type.
(cherry picked from commit 6270d3eeaf17b50abc4f8f4d97790d66179638e4)

Co-authored-by: Kyungmin Lee <rekyungmin@gmail.com>
Lib/tempfile.py
Lib/test/test_tempfile.py
Misc/NEWS.d/next/Library/2021-09-14-15-52-47.bpo-45192.DjA-BI.rst [new file with mode: 0644]

index 770f72c25295cbe756ef32b618682090e6b09b1b..eafce6f25b6fb296369a9fa5ac8700aa3a7041eb 100644 (file)
@@ -88,6 +88,10 @@ def _infer_return_type(*args):
     for arg in args:
         if arg is None:
             continue
+
+        if isinstance(arg, _os.PathLike):
+            arg = _os.fspath(arg)
+
         if isinstance(arg, bytes):
             if return_type is str:
                 raise TypeError("Can't mix bytes and non-bytes in "
index 7dbbf9b7e51e25156a4798726217372cbe6ec17f..8ad1bb98e8e89996dde23cdf85a6db4624f6fa25 100644 (file)
@@ -60,6 +60,25 @@ class TestLowLevelInternals(unittest.TestCase):
     def test_infer_return_type_pathlib(self):
         self.assertIs(str, tempfile._infer_return_type(pathlib.Path('/')))
 
+    def test_infer_return_type_pathlike(self):
+        class Path:
+            def __init__(self, path):
+                self.path = path
+
+            def __fspath__(self):
+                return self.path
+
+        self.assertIs(str, tempfile._infer_return_type(Path('/')))
+        self.assertIs(bytes, tempfile._infer_return_type(Path(b'/')))
+        self.assertIs(str, tempfile._infer_return_type('', Path('')))
+        self.assertIs(bytes, tempfile._infer_return_type(b'', Path(b'')))
+        self.assertIs(bytes, tempfile._infer_return_type(None, Path(b'')))
+        self.assertIs(str, tempfile._infer_return_type(None, Path('')))
+
+        with self.assertRaises(TypeError):
+            tempfile._infer_return_type('', Path(b''))
+        with self.assertRaises(TypeError):
+            tempfile._infer_return_type(b'', Path(''))
 
 # Common functionality.
 
diff --git a/Misc/NEWS.d/next/Library/2021-09-14-15-52-47.bpo-45192.DjA-BI.rst b/Misc/NEWS.d/next/Library/2021-09-14-15-52-47.bpo-45192.DjA-BI.rst
new file mode 100644 (file)
index 0000000..7dd9795
--- /dev/null
@@ -0,0 +1,5 @@
+Fix the ``tempfile._infer_return_type`` function so that the ``dir``
+argument of the :mod:`tempfile` functions accepts an object implementing the
+``os.PathLike`` protocol.
+
+Patch by Kyungmin Lee.