Skip to content
New issue

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

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

Already on GitHub? # to your account

Strange type expected from inferred dict #14499

Open
Garrett-R opened this issue Jan 21, 2023 · 2 comments
Open

Strange type expected from inferred dict #14499

Garrett-R opened this issue Jan 21, 2023 · 2 comments
Labels
bug mypy got something wrong

Comments

@Garrett-R
Copy link

Bug Report

Strange inference with dict.

To Reproduce

The repro is found in this Mypy playground, but here it is for convenience:

import random

value: str|None = None

if random.random() > 0.5:
    my_dict = {'a': False, 'b': None}
else:
    my_dict = {'a': True, 'b': value}

Expected Behavior

No error.

Actual Behavior

Error: main.py:8: error: Dict entry 1 has incompatible type "str": "Optional[str]"; expected "str": "Optional[bool]" [dict-item

Your Environment

  • Mypy version used: 0.911
  • Python version used: 3.11
@Garrett-R Garrett-R added the bug mypy got something wrong label Jan 21, 2023
@gandhis1
Copy link

I believe this is the same issue as #2008.

@hauntsaninja
Copy link
Collaborator

This isn't related to #2008, which talks about how to narrow types of symbols that have a declared type.

There is no declared type here, adding one would remove the error, e.g.

my_dict: dict[str, bool | str | None]
if random.random() > 0.5:
    my_dict = {'a': False, 'b': None}
else:
    my_dict = {'a': True, 'b': value}

You may also want to use a TypedDict

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants