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:

  1. class MyContext:
  2. ...
  3. def __exit__(self, exc, value, tb) -> bool: # Error
  4. print('exit')
  5. return False

This produces the following output from mypy:

  1. example.py:3: error: "bool" is invalid as return type for "__exit__" that always returns False
  2. example.py:3: note: Use "typing_extensions.Literal[False]" as the return type or change it to
  3. "None"
  4. example.py:3: note: If return type of "__exit__" implies that it may return True, the context
  5. manager may swallow exceptions

You can use Literal[False] to fix the error:

  1. from typing_extensions import Literal
  2.  
  3. class MyContext:
  4. ...
  5. def __exit__(self, exc, value, tb) -> Literal[False]: # OK
  6. print('exit')
  7. return False

You can also use None:

  1. class MyContext:
  2. ...
  3. def __exit__(self, exc, value, tb) -> None: # Also OK
  4. print('exit')