Skip to content

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

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
jamesbraza opened this issue Jan 12, 2021 · 2 comments
Labels
bug mypy got something wrong

Comments

@jamesbraza
Copy link
Contributor

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
@jamesbraza jamesbraza added the bug mypy got something wrong label Jan 12, 2021
@jamesbraza jamesbraza changed the title Using non-Literals in Literal contexts not working (false positive error) Using non-Literals in Literal contexts not working when used as Dict key (false positive error) Jan 12, 2021
@hauntsaninja
Copy link
Collaborator

From the linked section of PEP 586:

Literal types follow the existing rules regarding subtyping with no additional special-casing.

If you use a str subclass as your key, you'll get the same result (python/typing#445)

@jamesbraza
Copy link
Contributor Author

Thank you @hauntsaninja for pointing out that ticket, I now understand why it's actually an error.

Aside: you're doing great work with mypy, thank you!

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