Skip to content

Commit 6270d3e

Browse files
authored
bpo-45192: Fix a bug that infers the type of an os.PathLike[bytes] object as str (GH-28323)
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.
1 parent bc85eb7 commit 6270d3e

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

Lib/tempfile.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,10 @@ def _infer_return_type(*args):
8888
for arg in args:
8989
if arg is None:
9090
continue
91+
92+
if isinstance(arg, _os.PathLike):
93+
arg = _os.fspath(arg)
94+
9195
if isinstance(arg, bytes):
9296
if return_type is str:
9397
raise TypeError("Can't mix bytes and non-bytes in "

Lib/test/test_tempfile.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,25 @@ def test_infer_return_type_multiples_and_none(self):
6262
def test_infer_return_type_pathlib(self):
6363
self.assertIs(str, tempfile._infer_return_type(pathlib.Path('/')))
6464

65+
def test_infer_return_type_pathlike(self):
66+
class Path:
67+
def __init__(self, path):
68+
self.path = path
69+
70+
def __fspath__(self):
71+
return self.path
72+
73+
self.assertIs(str, tempfile._infer_return_type(Path('/')))
74+
self.assertIs(bytes, tempfile._infer_return_type(Path(b'/')))
75+
self.assertIs(str, tempfile._infer_return_type('', Path('')))
76+
self.assertIs(bytes, tempfile._infer_return_type(b'', Path(b'')))
77+
self.assertIs(bytes, tempfile._infer_return_type(None, Path(b'')))
78+
self.assertIs(str, tempfile._infer_return_type(None, Path('')))
79+
80+
with self.assertRaises(TypeError):
81+
tempfile._infer_return_type('', Path(b''))
82+
with self.assertRaises(TypeError):
83+
tempfile._infer_return_type(b'', Path(''))
6584

6685
# Common functionality.
6786

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Fix the ``tempfile._infer_return_type`` function so that the ``dir``
2+
argument of the :mod:`tempfile` functions accepts an object implementing the
3+
``os.PathLike`` protocol.
4+
5+
Patch by Kyungmin Lee.

0 commit comments

Comments
 (0)