You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Improve error message from os.fspath if __fspath__ is set to None #106046
A common Python idiom is to set a magic method to None in a subclass if you want to disable the behaviour that the magic method enables. If you do so, a nice error message will be given if a user tries to "call" the magic method that's been set to None. For example:
>>> classFoo(list):
... __iter__=None
...
>>> iter(Foo())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Foo' object is not iterable
>>> classBar(int):
... __hash__=None
...
>>> hash(Bar(42))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'Bar'
However, Python doesn't currently do the same thing for __fspath__. If a subclass of an os.PathLike sets __fspath__ to None, Python gives a bad error message when os.fspath is called on instances of that subclass:
>>> from pathlib import Path
>>> import os
>>> classBaz(Path):
... __fspath__=None
...
>>> os.fspath(Baz())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
Pitch
It would be nice if Python handled __fspath__ being set to None the same way it handles magic methods such as __iter__ or __hash__ being set to None. The error message in such cases should be the expected str, bytes or os.PathLike object, not Baz error message that the interpreter gives when os.fspath is called on an object that has no __fspath__ method at all.
Yeah. I don't think there's any guarantee or promise that Python will do this for every magic method -- but if we have a use case here, then it could be worth it to implement it for __fspath__.
Activity
barneygale commentedon Jun 23, 2023
It also doesn't work for
__bytes__():AlexWaygood commentedon Jun 23, 2023
Yeah. I don't think there's any guarantee or promise that Python will do this for every magic method -- but if we have a use case here, then it could be worth it to implement it for
__fspath__.pythongh-106046: Improve error message from `os.fspath` if `__fspath_…
gh-106046: Improve error message from `os.fspath` if `__fspath__` is …