Skip to content

All standard library functions accepting str paths must accept PathLike as well #102425

Open
@arhadthedev

Description

@arhadthedev

Inspired by gh-3484 that tried to fix this for wave.open() only but failed.

We need a centralized and universal approach instead so everything accepting str paths could automatically accept PathLike for free.

For this, we can amend stdlib functions to wrap their path arguments into pathlib.PurePath introduced in Python 3.4. Unlike os.fspath, it throws a nicely formatted exception for us:

  • os.fspath from the mentioned bpo-31412: wave.open takes a path-like object #3484:

    cpython/Lib/aifc.py

    Lines 912 to 918 in 4a82d65

    try:
    f = os.fspath(f)
    except TypeError:
    if not hasattr(f, 'read') and not hasattr(f, 'write'):
    raise TypeError('open() takes str, a path-like object, '
    + 'or an open file-like object, '
    + f'not {type(f).__name__!r}') from None

  • PurePath:

    >>> import pathlib
    >>> pathlib.PurePath(16)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "D:\Oleg\cpython\Lib\pathlib.py", line 267, in __new__
        return cls._from_parts(args)
               ^^^^^^^^^^^^^^^^^^^^^
      File "D:\Oleg\cpython\Lib\pathlib.py", line 316, in _from_parts
        drv, root, parts = self._parse_args(args)
                           ^^^^^^^^^^^^^^^^^^^^^^
      File "D:\Oleg\cpython\Lib\pathlib.py", line 300, in _parse_args
        a = os.fspath(a)
            ^^^^^^^^^^^^
    TypeError: expected str, bytes or os.PathLike object, not int

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirinterpreter-core(Objects, Python, Grammar, and Parser dirs)stdlibPython modules in the Lib dirtopic-IOtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions