[Python-ideas] tweaking the file system path protocol
Steven D'Aprano
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
> (os._fspath):
>
> 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)?
class str:
def __fspath__(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.
def fspath(path):
try:
dunder = type(path).__fspath__
except AttributeError:
raise TypeError(...) from None
else:
if dunder is not None:
result = dunder(path)
if type(result) in (str, byte):
return result
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
the subclass.
--
Steve
More information about the Python-ideas
mailing list