You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
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.
Activity
rwbarton commentedon Jun 15, 2016
In the first call to
f, mypy infers the typeDict[AbstractSet[str], int]for the expression{frozenset(['a']): 1}, because that's what is needed for the argument tof. In the definition ofx, mypy infers the typeDict[frozenset[str], int]for the variablexbased on its initial value of{frozenset(['a']): 1}, not taking the later call tofinto account.Dict[frozenset[str], int]is not a subtype ofDict[AbstractSet[str], int](even thoughfrozenset[str]is a subtype ofAbstractSet[str]) because aDict[AbstractSet[str], int]is a mutable object into which you can insert arbitraryAbstractSet[str]keys, and that is not true of aDict[frozenset[str], int]. Herefcould modify its argument and thenxwould no longer really be aDict[frozenset[str], int].If
fdoesn't actually modify its argument, then it's better to give the argument a type likeMapping[AbstractSet[str], int]. This won't actually let your program type check yet, but it should after python/typeshed#278 is fixed.JukkaL commentedon Jun 15, 2016
This might be worth explaining in the Common issues section of mypy documentation.
berdario commentedon Mar 18, 2019
FWIW, even after the work on #278 and #1044, by defining f as
There'll be a
Argument 1 to "f" has incompatible type "Dict[FrozenSet[str], int]"; expected "Mapping[AbstractSet[str], int]"yieldedilevkivskyi commentedon Mar 18, 2019
Because
Mappingis invariant in key type.