Skip to content

Set operators confusion #7236

Closed
Closed
@kaste

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.

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