Skip to content

Set operators confusion聽#7236

Closed
Closed

Description

@kaste

Hi 馃憢 ! I have the following test code:

from collections import defaultdict
from typing import Any, DefaultDict, Dict, Iterable, Set

def xs(xs: Iterable[str]) -> None:
    ...

d: Dict[str, str] = {}
xs(d.keys() - {'2'}) # 1
xs(d.keys() - {2}) # 2
xs(d.keys() - {2} - {'2'}) # 3
xs(d.keys() - {'2'} - {2}) # 4

image

 10:15  error  mypy  Argument 1 to <set> has incompatible type "int"; expected "str"
 11:1   error  mypy  Argument 1 to "xs" has incompatible type "AbstractSet[Union[str, int]]"; expected
                     "Iterable[str]"

Discussion:

1 is obviously OK; 2 is obviously okay bc a type checker should report here.
3 is not ok although a type checker must report something. The result of the expression is not Union[str, int} and the call to xs is okay. mypy should report the same as in 2 imo
4 surprisingly passes although it's just 3 flipped which is not ok. A type checker should report here with the same error as 2.

Further: If I change the def of xs to

def xs(xs: Set[str]) -> None:
    ...

all 4 calls fail because mypy wants me to use AbstractSet instead of just Set here. This is very unintuitive bc this is just a concrete function over sets, in a code review I would not even know if Set implements something that AbstractSet does not have etc.

Activity

  1. ilevkivskyi commented on Aug 12, 2019

    @ilevkivskyi
    Member

    all 4 calls fail because mypy wants me to use AbstractSet instead of just Set here. This is very unintuitive bc this is just a concrete function over sets, in a code review I would not even know if Set implements something that AbstractSet does not have etc.

    What do you mean by "unintuitive"? Accepting KeysView where a Set is expected would be just wrong. Mypy has couple similar exceptions, but only in widely used cases where danger is minimal: for example int is considered a subtype of float although it is not the case at runtime.

  2. ilevkivskyi commented on Aug 12, 2019

    @ilevkivskyi
    Member

    Anyway, I agree that example 4 should give an error, although I think this is a typeshed issue (there are some Anys used in AbstractSet methods). I would propose to continue a discussion on that tracker, please open an issue there.

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