Skip to content

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

@Capruce

Description

@Capruce

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy