Skip to content

Type Inference on dict-literals with values of Optional[Any] ignores non-optional values. #9544

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

Closed
Capruce opened this issue Oct 7, 2020 · 1 comment
Labels
bug mypy got something wrong

Comments

@Capruce
Copy link

Capruce commented Oct 7, 2020

Bug Report

If a dict literal contains a value of type Optional[Any], other optional values (e.g. Optional[T1], Optional[T2]), and non optional (non-overlapping) values (e.g. T3, T4), then its inferred type is dict[KeyType*, Union[T1, None, T2]] ignoring Any, T3, and T4.

To Reproduce

from datetime import datetime
from decimal import Decimal
from typing import Any, Optional

optional_any: Optional[Any]
optional_string: Optional[str]
optional_int: Optional[int]
my_dict = {
    "datetime": datetime(2020, 1, 1),
    "Decimal": Decimal("2000"),
    "optional_any": optional_any,
    "optional_str": optional_string,
    "optional_int": optional_int,
}
reveal_type(my_dict)

Output from mypy is:

scratchfile.py:9: error: Dict entry 0 has incompatible type "str": "datetime"; expected "str": "Union[str, None, int]"  [dict-item]
scratchfile.py:10: error: Dict entry 1 has incompatible type "str": "Decimal"; expected "str": "Union[str, None, int]"  [dict-item]
scratchfile.py:15: note: Revealed type is 'builtins.dict[builtins.str*, Union[builtins.str, None, builtins.int]]'

Expected Behavior

I would've expected the inferred type of my_dict to be dict[str*, Union[Any, str, None, int, Decimal, datetime]]
Or just reduce to dict[str*, object*]

Your Environment

  • Mypy version used: 0.782
  • Mypy command-line flags: --show-error-codes
  • Python version used: Tested on 3.6.9 and 3.7.3
  • Operating system and version: macOS Catalina Version 10.15.6

I can work around this quite easily (by either type: ignore, or cast on the Any) But thought I'd raise it in case this isn't expected behaviour.

@Capruce Capruce added the bug mypy got something wrong label Oct 7, 2020
@hauntsaninja
Copy link
Collaborator

I believe this is fixed on master in #9301 / dupe of #9425

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

No branches or pull requests

2 participants