Skip to content

Set operators confusion #7236

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
kaste opened this issue Jul 18, 2019 · 2 comments
Closed

Set operators confusion #7236

kaste opened this issue Jul 18, 2019 · 2 comments

Comments

@kaste
Copy link

kaste commented Jul 18, 2019

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.

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

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

No branches or pull requests

2 participants