Skip to content

Dict[AbstractSet, Any] weird type error #1711

Closed

Description

@berdario

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

Activity

  1. rwbarton commented on Jun 15, 2016

    @rwbarton
    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.

  2. JukkaL commented on Jun 15, 2016

    @JukkaL
    Collaborator

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

  3. berdario commented on Mar 18, 2019

    @berdario
    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

  4. ilevkivskyi commented on Mar 18, 2019

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

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