Check the return type of exit [exit-return]
If mypy can determine that exit
always returns False
, mypychecks that the return type is not bool
. The boolean value ofthe return type affects which lines mypy thinks are reachable after awith
statement, since any exit
method that can returnTrue
may swallow exceptions. An imprecise return type can resultin mysterious errors reported near with
statements.
To fix this, use either typing_extensions.Literal[False]
orNone
as the return type. Returning None
is equivalent toreturning False
in this context, since both are treated as falsevalues.
Example:
- class MyContext:
- ...
- def __exit__(self, exc, value, tb) -> bool: # Error
- print('exit')
- return False
This produces the following output from mypy:
- example.py:3: error: "bool" is invalid as return type for "__exit__" that always returns False
- example.py:3: note: Use "typing_extensions.Literal[False]" as the return type or change it to
- "None"
- example.py:3: note: If return type of "__exit__" implies that it may return True, the context
- manager may swallow exceptions
You can use Literal[False]
to fix the error:
- from typing_extensions import Literal
- class MyContext:
- ...
- def __exit__(self, exc, value, tb) -> Literal[False]: # OK
- print('exit')
- return False
You can also use None
:
- class MyContext:
- ...
- def __exit__(self, exc, value, tb) -> None: # Also OK
- print('exit')