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

"Cannot determine type" if first assignment to attribute is unreachable #9709

Open
mthuurne opened this issue Nov 9, 2020 · 0 comments
Open
Labels
bug mypy got something wrong topic-inference When to infer types or require explicit annotations topic-reachability Detecting unreachable code

Comments

@mthuurne
Copy link
Contributor

mthuurne commented Nov 9, 2020

To Reproduce

Run mypy on the following code:

class C:
    def __init__(self, a: str) -> None:
        if a is None:
            self.x = 123
        else:
            self.x = 456

It will output:

testcase.py:6: error: Cannot determine type of 'x'

Line 6 contains the second assignment to self.x.

Expected Behavior

mypy should be able to determine that the type of C.x is int.

Actual Behavior

The fact that a is annotated as str means that mypy determines that a is None is never true and therefore the first assignment to self.x is unreachable. The problem disappears if a is annotated as Optional[str].

So it looks like mypy half-ignores the first assignment to self.x: it doesn't use the type information available there since the code is unreachable, but it still considers it the assignment that determines the type of self.x.

Your Environment

mypy 0.790 with default configuration, running on Python 3.8.5 on openSUSE Linux.

@mthuurne mthuurne added the bug mypy got something wrong label Nov 9, 2020
@AlexWaygood AlexWaygood added topic-reachability Detecting unreachable code topic-inference When to infer types or require explicit annotations labels Apr 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-inference When to infer types or require explicit annotations topic-reachability Detecting unreachable code
Projects
None yet
Development

No branches or pull requests

2 participants