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

Mypy should detect obvious UnboundLocalErrors (e.g. declarations missing from an else: branch) #13696

Closed
lukasjuhrich opened this issue Sep 20, 2022 · 1 comment
Labels

Comments

@lukasjuhrich
Copy link

Feature

If a variable is only declared in an if branch, but used afterwards, mypy should throw an error.

Pitch

Currently, the following snippet passes mypy --strict (v0.971/py3.9):

import typing as t
def foo(val: t.Optional[str] = None) -> int:
    if val is not None:
        derived_val = 1
    reveal_type(derived_val)
    return derived_val

Additionally, it reveals builtins.int for a clearly underspecified type.
This is pretty surprising, and in fact I did not catch an obvious bug because I mistakenly remembered that mypy had warned me about such issues in the past – but also because I assumed imypy could not possibly infer int in such a case: If I had a conflicting declaration in the else block, mypy would have already complained! So to some extent one might say this violates the principle of least surprise.

Relates to #686 and #6233 (specifically this comment).
(I hope this is not a duplicate)

lukasjuhrich added a commit to agdsn/hades that referenced this issue Sep 20, 2022
lukasjuhrich added a commit to agdsn/hades that referenced this issue Sep 20, 2022
@JelleZijlstra
Copy link
Member

Duplicate of #686 and #4019.

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

No branches or pull requests

2 participants