Skip to content

Mapping invariant on key? #16103

Closed as not planned
Closed as not planned

Description

@gsakkis

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?

Activity

  1. hauntsaninja commented on Sep 13, 2023

    @hauntsaninja
    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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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