Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Erroneous "missing return statement" using ExitStack #7726

Closed
wadetregaskis-linkedin opened this issue Oct 16, 2019 · 4 comments
Closed

Erroneous "missing return statement" using ExitStack #7726

wadetregaskis-linkedin opened this issue Oct 16, 2019 · 4 comments

Comments

@wadetregaskis-linkedin
Copy link

test.py:

from contextlib import ExitStack

def context_manager_with_return_bug() -> int:
    with ExitStack() as stack:
        return 5

mypy complains: test.py:3: error: Missing return statement

Oddly this only seems to happen when using ExitStack specifically - no other context manager, based on other functions / classes / etc, in my codebase triggers this bug.

@ilevkivskyi
Copy link
Member

The ExitStack() is annotated in typeshed as something that can swallow exceptions. This kind of matches the docs (if any of the context managers in the stack swallows exceptions).

Of course in this simplified case there is nothing that can raise an exception in the first place. But I assume your code is more complex. I think the best way forward is to just silence it by adding:

assert False, "unreachable"

after the context manager.

In principle we can add some special-casing for ExitStack() and/or add a concept of non-raising statements. This may be tricky to add, so I think this is low priority.

@wadetregaskis-linkedin
Copy link
Author

Ah, that makes sense, I hadn't considered that behaviour of ExitStack… seems this is working as intended - though maybe the error message from mypy could be improved to explain this better, e.g. "Missing return - the managed context using ExitStack can turn exceptions thrown inside the context into silently jumping to & falling off the end of the context.".

@ilevkivskyi
Copy link
Member

maybe the error message from mypy could be improved to explain this better

Yes, this is one of the potential ways to improve this, see also #7666

@hauntsaninja
Copy link
Collaborator

The actionable thing here is #7666

@hauntsaninja hauntsaninja closed this as not planned Won't fix, can't repro, duplicate, stale Aug 25, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants