Title: The tempfile._infer_return_type function cannot infer the type of os.PathLike objects.
Type: behavior Stage: patch review
Components: Library (Lib) Versions: Python 3.10, Python 3.9, Python 3.8, Python 3.7, Python 3.6
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: rekyungmin
Priority: normal Keywords: patch

Created on 2021-09-14 05:44 by rekyungmin, last changed 2021-09-14 06:05 by rekyungmin.

Pull Requests
URL Status Linked Edit
PR 28323 open rekyungmin, 2021-09-14 06:05
Messages (2)
msg401754 - (view) Author: Kyungmin Lee (rekyungmin) * Date: 2021-09-14 05:44
The tempfile module has been updated to accept an object implementing os.PathLike protocol for path-related parameters as of Python 3.6 (e.g. dir parameter). An os.PathLike object represents a filesystem path as a str or bytes object (i.e. def __fspath__(self) -> Union[str, bytes]:). However, if an object implementing os.PathLike[bytes] is passed as a dir argument, a TypeError is raised. This bug occurs because the tempfile._infer_return_type function considers all objects other than bytes as str type.
msg401755 - (view) Author: Kyungmin Lee (rekyungmin) * Date: 2021-09-14 05:50
for example:

from typing import Union

class FakePath:
    def __init__(self, path):
        self.path = path

    def __fspath__(self) -> Union[str, bytes]:
        return self.path

if __name__ == "__main__":
    from tempfile import TemporaryDirectory

    # You need to create `existing_path` directory

    with TemporaryDirectory(dir=FakePath("existing_path")) as str_path:
        print(str_path)  # 'existing_path/...'

    with TemporaryDirectory(dir=FakePath(b"existing_path")) as byte_path:
        print(byte_path)  # expected b'existing_path/...' but raised TypeError

Date User Action Args
2021-09-14 06:05:55rekyungminsetkeywords: + patch
stage: patch review
pull_requests: + pull_request26732
2021-09-14 05:50:24rekyungminsetmessages: + msg401755
2021-09-14 05:44:04rekyungmincreate