[issue44196] Document that importlib.abc.Traversable's methods should raise FileNotFoundError

Jason R. Coombs report at bugs.python.org
Sun May 23 13:18:47 EDT 2021


Jason R. Coombs <jaraco at jaraco.com> added the comment:

Having a look at the `open` function (https://docs.python.org/3/library/functions.html#open), it does not define which exceptions might be thrown. Similarly for pathlib.Path.open (https://docs.python.org/3/library/pathlib.html#pathlib.Path.open) and zipfile.Path.open (https://docs.python.org/3/library/zipfile.html#zipfile.Path.open).

And since the canonical implementation of a Traversable resource is those two Path classes, it seems infeasible for the protocol to enforce a specific constraint on the available exceptions.

I think the best this protocol can do is advertise that the underlying implementation may raise an Exception if the target indicated by self cannot be opened (allowing for an Exception where appropriate), but in my opinion, that's the default interface for any protocol (or function) unless otherwise specified.

I don't want to explicitly call out FileNotFoundError or IsADirectoryError because those exceptions happen to be the most common. Consider for example the case where permission is not granted for read:

```
$ pathlib.Path('./foo').open()
PermissionError: [Errno 13] Permission denied: 'foo'
```

That's yet another case where Traversable.open might raise something other than FileNotFoundError.

In my opinion, unless the Traversable objects are expected to handle or transform exceptions, it's fine to simply delegate to the underlying implementations and allow any exceptions to bubble through.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44196>
_______________________________________


More information about the Python-bugs-list mailing list