Skip to content

Improve error message from os.fspath if __fspath__ is set to None #106046

Closed
@AlexWaygood

Description

@AlexWaygood

Feature or enhancement

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:

>>> class Foo(list):
...     __iter__ = None
...
>>> iter(Foo())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Foo' object is not iterable
>>> class Bar(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
>>> class Baz(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.

Linked PRs

Metadata

Metadata

Assignees

Labels

type-featureA feature request or enhancement

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions