Skip to content
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

Mapping invariant on key? #16103

Closed
gsakkis opened this issue Sep 13, 2023 · 1 comment
Closed

Mapping invariant on key? #16103

gsakkis opened this issue Sep 13, 2023 · 1 comment
Labels
bug mypy got something wrong

Comments

@gsakkis
Copy link

gsakkis commented Sep 13, 2023

It seems that Mapping[k, v] is invariant to k, but not when a dict literal is passed.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=4195e62f5ea8fa4b027988aa9174bb7c

main.py:25: error: Argument 1 to "test_map_key" has incompatible type "Mapping[str, int]"; expected "Mapping[str | int, Any]"  [arg-type]
  1. Why is this an error? Mapping is immutable so it shouldn't matter that the passed key is more constrained that what is expected.
  2. Why does passing a dict literal work?
@gsakkis gsakkis added the bug mypy got something wrong label Sep 13, 2023
@hauntsaninja
Copy link
Collaborator

  1. See e.g. Make Mapping covariant in keys (too). typing#273 (comment) and Reconsider making Mapping covariant in the key type typing#445
  2. Passing a dict literal works because mypy is able to infer the static type from type context. When you assign variables, mypy uses the explicit type hint or infers a type for the variable from the expression in the left hand side.

@hauntsaninja hauntsaninja closed this as not planned Won't fix, can't repro, duplicate, stale Sep 13, 2023
@sterliakov sterliakov marked this as a duplicate of #18494 Jan 20, 2025
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