Skip to content

[3.10] bpo-45192: Fix a bug that infers the type of an os.PathLike[bytes] object as str (GH-28323) #29111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Lib/tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,25 @@ def test_infer_return_type_multiples_and_none(self):
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.

Expand Down
Original file line number Diff line number Diff line change
@@ -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.