python-trio / trio-typing

Type hints for Trio and related projects
Other
27 stars 14 forks source link

Mark context manager exits that can't swallow exceptions as returning None #20

Closed oremanj closed 4 years ago

oremanj commented 4 years ago

If the __exit__ is marked as returning bool, recent versions of mypy will assume it can swallow exceptions and will complain that code like

def fn() -> int:
  with context():
    if something:
      raise ValueError
    return 42

has a missing return statement after the with.

CancelScope can swallow exceptions, and in most cases where you'd use a cancel scope you care about the control flow when cancelled, so it keeps a bool return type from __exit__.

open_nursery() is declared to return an aribtrary AsyncContextManager[None] and mypy empirically does not seem to assume that those might swallow exceptions for control flow purposes. Nurseries contain a cancel scope, so if anyone says nursery.cancel_scope.cancel() then the "jump to right after the nursery" control flow path will exist. Not all uses of a nursery will directly access its cancel scope, though, so it seems better to me to avoid the false positive in this case.