python-trio / trio-typing

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

Fix return type of `CancelScope.__exit__` such that it can suppresses errors #94

Closed rsokl closed 1 month ago

rsokl commented 1 month ago

The current return type of CancelScope.__exit__ is bool | None, which tells type checkers that CancelScope cannot suppress errors:

https://typing.readthedocs.io/en/latest/spec/exceptions.html#context-managers

If the return type of the exit method is specifically bool or Literal[True], a type checker should assume that exceptions can be suppressed. For any other return type, a type checker should assume that exceptions are not suppressed. Examples include: Any, Literal[False], None, and bool | None.

This is bad. If there were ever a context manager that could suppress errors, it would be CancelScope 😄

Given:

def f()
    with trio.move_on_after(10):
        while True:
            await trio.sleep(20)
            return 2
     return None

Before: pyright says the return type of f is int. I.e. it thinks the return None is unreachable After: pyright says the return type of f is int | None, which is correct.

trio-bot[bot] commented 1 month ago

Hey @rsokl, it looks like that was the first time we merged one of your PRs! Thanks so much! :tada: :birthday:

If you want to keep contributing, we'd love to have you. So, I just sent you an invitation to join the python-trio organization on Github! If you accept, then here's what will happen:

If you want to read more, here's the relevant section in our contributing guide.

Alternatively, you're free to decline or ignore the invitation. You'll still be able to contribute as much or as little as you like, and I won't hassle you about joining again. But if you ever change your mind, just let us know and we'll send another invitation. We'd love to have you, but more importantly we want you to do whatever's best for you.

If you have any questions, well... I am just a humble Python script, so I probably can't help. But please do post a comment here, or in our chat, or on our forum, whatever's easiest, and someone will help you out!

oremanj commented 1 month ago

@rsokl Thank you for the fix, but please note that trio-typing is somewhat unloved now that trio comes with built-in support for type hints. Please consider using those instead - they were already correct in this respect :-)