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

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

Closed
ghost opened this issue Oct 16, 2019 · 2 comments

Comments

@ghost
Copy link

ghost commented Oct 16, 2019

  • 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

@ilevkivskyi
Copy link
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

@ilevkivskyi
Copy link
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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant