Skip to content

Can't infer T where T is Mapping[str, int] or Mapping[K, V], but works for sequence #7727

Closed

Description

  • Are you reporting a bug, or opening a feature request?
    bug

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.

from typing import Mapping, Sequence, TypeVar

E = TypeVar("E")
K = TypeVar("K")
V = TypeVar("V")
T = TypeVar("T")

def choose_one_of(a: T, b: T) -> T:
    return a

def empty_sequence() -> Sequence[E]:
    return []

def empty_mapping() -> Mapping[K, V]:
    return {}

def choose_seq(s: Sequence[int]) -> Sequence[int]:
    x = choose_one_of(s, empty_sequence())
    return x

def choose_mapping(m: Mapping[str, int]) -> Mapping[str, int]:
   x = choose_one_of(m, empty_mapping())
   return x

print(choose_seq([]))
print(choose_mapping({}))
  • What is the actual behavior/output?

a.py:23: error: Incompatible return value type (got "object", expected "Mapping[str, int]")

  • What is the behavior/output you expect?

No error.

Interestingly, there is no error if empty_mapping returns Mapping[str, V] (or Mapping[str, int]), but there is still an error if it returns Mapping[K, int].

  • What are the versions of mypy and Python you are using?
    Do you see the same issue after installing mypy from Git master?

mypy --version is mypy 0.740+dev.222b14d904a0e359bec934fd81d67d981abdada4
python --version is Python 3.7.4

  • What are the mypy flags you are using? (For example --strict-optional)

None

Activity

  1. ilevkivskyi commented on Oct 18, 2019

    @ilevkivskyi
    Member

    This is actually related to the fact that Mapping is invariant in key type (but not in value type as you observe).

    So this is essentially a duplicate of python/typing#445

  2. ilevkivskyi commented on Oct 18, 2019

    @ilevkivskyi
    Member

    Note that #6613 when applied to mapping key type will also solve this I think.

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

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions