Skip to content

Using non-Literals in Literal contexts not working when used as Dict key (false positive error) #9899

Closed
@jamesbraza

Description

@jamesbraza

Bug Report

Before I begin, I would like to say that I am a big fan of PEP 586's Literal type.

To Reproduce

Here is some sample code that exposes (what I believe is) a break from Using non-Literals in Literal contexts part of PEP 586.

from typing import Any, Dict, Literal

Keys = Literal["foo", "bar"]


def get_some_dict() -> Dict[str, Any]:
    foo_bar: Dict[Keys, Any] = {"foo": 0, "bar": 1}
    return foo_bar  # error: Incompatible return value type
    # (got "Dict[Union[Literal['foo'], Literal['bar']], Any]",
    # expected "Dict[str, Any]")  [return-value]

Expected Behavior

In my opinion, this is basically the textbook case of using a non-Literal in a Literal context.

In other words, the Literal here can only be a str, so mypy shouldn't error on the keys type compatibility.

Actual Behavior

Here's the output of mypy:

path/to/literal_and_dict.py: note: In function "get_some_dict":
path/to/literal_and_dict.py:8:12: error: Incompatible return value type (got "Dict[Union[Literal['foo'], Literal['bar']], Any]", expected "Dict[str, Any]")  [return-value]

Your Environment

  • Mypy version used: current master 0.800+dev.3497675c5f7917eb0e8ad4b7e2b7f3bc4cfd52dc
  • Mypy command-line flags: none notable
  • Mypy configuration options from mypy.ini (and other config files): none notable
  • Python version used: 3.8.6
  • Operating system and version: macOS 10.15.7

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