Skip to content

Dict[AbstractSet, Any] weird type error #1711

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
berdario opened this issue Jun 15, 2016 · 4 comments
Closed

Dict[AbstractSet, Any] weird type error #1711

berdario opened this issue Jun 15, 2016 · 4 comments

Comments

@berdario
Copy link

I get Argument 1 to "f" has incompatible type Dict[frozenset[str], int]; expected Dict[AbstractSet[str], int]

with the following code:

from typing import AbstractSet, Dict

def f(v: Dict[AbstractSet[str], int]):
    pass

f({frozenset(['a']): 1})  # this works
x = {frozenset(['a']): 1}
f(x) # this fails
@rwbarton
Copy link
Contributor

In the first call to f, mypy infers the type Dict[AbstractSet[str], int] for the expression {frozenset(['a']): 1}, because that's what is needed for the argument to f. In the definition of x, mypy infers the type Dict[frozenset[str], int] for the variable x based on its initial value of {frozenset(['a']): 1}, not taking the later call to f into account.

Dict[frozenset[str], int] is not a subtype of Dict[AbstractSet[str], int] (even though frozenset[str] is a subtype of AbstractSet[str]) because a Dict[AbstractSet[str], int] is a mutable object into which you can insert arbitrary AbstractSet[str] keys, and that is not true of a Dict[frozenset[str], int]. Here f could modify its argument and then x would no longer really be a Dict[frozenset[str], int].

If f doesn't actually modify its argument, then it's better to give the argument a type like Mapping[AbstractSet[str], int]. This won't actually let your program type check yet, but it should after python/typeshed#278 is fixed.

@JukkaL
Copy link
Collaborator

JukkaL commented Jun 15, 2016

This might be worth explaining in the Common issues section of mypy documentation.

@berdario
Copy link
Author

FWIW, even after the work on #278 and #1044, by defining f as

def f(v: Mapping[AbstractSet[str], int]):
    pass

There'll be a Argument 1 to "f" has incompatible type "Dict[FrozenSet[str], int]"; expected "Mapping[AbstractSet[str], int]" yielded

@ilevkivskyi
Copy link
Member

Because Mapping is invariant in key type.

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

4 participants