[Python-ideas] tweaking the file system path protocol
steve at pearwood.info
Tue May 23 06:49:59 EDT 2017
On Tue, May 23, 2017 at 12:12:11PM +0200, Wolfgang Maier wrote:
> Here's how the proposal could be implemented in the pure Python version
> def _fspath(path):
> path_type = type(path)
> if path_type is str or path_type is bytes:
> return path
How about simplifying the implementation of fspath by giving str and
bytes a __fspath__ method that returns str(self) or bytes(self)?
return str(self) # Must be str, not type(self).
(1) We can avoid most of the expensive type checks.
(2) Subclasses of str and bytes don't have to do anything to get a
useful default behaviour.
dunder = type(path).__fspath__
raise TypeError(...) from None
if dunder is not None:
result = dunder(path)
if type(result) in (str, byte):
raise TypeError('expected a str or bytes, got ...')
The reason for the not None check is to allow subclasses to explicitly
deny that they can be used for paths by setting __fspath__ to None in
More information about the Python-ideas