[New-bugs-announce] [issue27161] Confusing exception in Path().with_name

Antony Lee report at bugs.python.org
Mon May 30 20:22:15 EDT 2016


New submission from Antony Lee:

`Path().with_name` can fail with a lot of different exceptions:

    >>> Path("foo").with_name(0)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/usr/lib/python3.5/pathlib.py", line 800, in with_name
        raise ValueError("Invalid name %r" % (name))
    ValueError: Invalid name 0

    >>> Path("foo").with_name(1)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/usr/lib/python3.5/pathlib.py", line 797, in with_name
        drv, root, parts = self._flavour.parse_parts((name,))
    File "/usr/lib/python3.5/pathlib.py", line 62, in parse_parts
        drv, root, rel = self.splitroot(part)
    File "/usr/lib/python3.5/pathlib.py", line 268, in splitroot
        if part and part[0] == sep:
    TypeError: 'int' object is not subscriptable

    >>> Path("foo").with_name({})
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/usr/lib/python3.5/pathlib.py", line 800, in with_name
        raise ValueError("Invalid name %r" % (name))
    ValueError: Invalid name {}

    >>> Path("foo").with_name({0: 1})
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/usr/lib/python3.5/pathlib.py", line 797, in with_name
        drv, root, parts = self._flavour.parse_parts((name,))
    File "/usr/lib/python3.5/pathlib.py", line 69, in parse_parts
        parsed.append(sys.intern(rel))
    TypeError: must be str, not dict

    >>> Path("foo").with_name({"a": "b"})
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/usr/lib/python3.5/pathlib.py", line 797, in with_name
        drv, root, parts = self._flavour.parse_parts((name,))
    File "/usr/lib/python3.5/pathlib.py", line 62, in parse_parts
        drv, root, rel = self.splitroot(part)
    File "/usr/lib/python3.5/pathlib.py", line 268, in splitroot
        if part and part[0] == sep:
    KeyError: 0

While most are fairly clear, the last one is particularly confusing IMO; additionally, looking at the implementation of `_Flavour.parse_parts` there seems to be room for even more confusion with a properly crafted dict.

Of course, with Python's dynamicity a lot of exceptions can be triggered at weird places using carefully crafted objects, but I think pathlib should at least raise a clear exception when passed an incorrect builtin type.

----------
components: Library (Lib)
messages: 266724
nosy: Antony.Lee
priority: normal
severity: normal
status: open
title: Confusing exception in Path().with_name
versions: Python 3.5, Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue27161>
_______________________________________


More information about the New-bugs-announce mailing list