mirror of
https://github.com/davidhalter/typeshed.git
synced 2026-08-06 16:08:29 +08:00
Make most contextmanager __exit__ signatures return Optional[bool] (#3179)
This pull request is a follow-up to https://github.com/python/mypy/issues/7214. In short, within that mypy issue, we found it would be helpful to determine between contextmanagers that can "swallow" exceptions vs ones that can't. This helps prevent some false positive when using flags that analyze control flow such as `--warn-unreachable`. To do this, Jelle proposed assuming that only contextmanagers where the `__exit__` returns `bool` are assumed to swallow exceptions. This unfortunately required the following typeshed changes: 1. The typing.IO, threading.Lock, and concurrent.futures.Executor were all modified so `__exit__` returns `Optional[None]` instead of None -- along with all of their subclasses. I believe these three types are meant to be subclassed, so I felt picking the more general type was correct. 2. There were also a few concrete types (e.g. see socketserver, subprocess, ftplib...) that I modified to return `None` -- I checked the source code, and these all seem to return None (and don't appear to be meant to be subclassable). 3. contextlib.suppress was changed to return bool. I also double-checked the unittest modules and modified a subset of those contextmanagers, leaving ones like `_AssertRaisesContext` alone.
This commit is contained in:
committed by
Jelle Zijlstra
parent
3cfc3150f0
commit
b294782183
@@ -292,6 +292,15 @@ Type variables and aliases you introduce purely for legibility reasons
|
||||
should be prefixed with an underscore to make it obvious to the reader
|
||||
they are not part of the stubbed API.
|
||||
|
||||
When adding type annotations for context manager classes, annotate
|
||||
the return type of `__exit__` as bool only if the context manager
|
||||
sometimes suppresses annotations -- if it sometimes returns `True`
|
||||
at runtime. If the context manager never suppresses exceptions,
|
||||
have the return type be either `None` or `Optional[bool]`. If you
|
||||
are not sure whether exceptions are suppressed or not or if the
|
||||
context manager is meant to be subclassed, pick `Optional[bool]`.
|
||||
See https://github.com/python/mypy/issues/7214 for more details.
|
||||
|
||||
NOTE: there are stubs in this repository that don't conform to the
|
||||
style described above. Fixing them is a great starting point for new
|
||||
contributors.
|
||||
|
||||
Reference in New Issue
Block a user