Skip to content

collections.abc.Set does not support Iterable s in some dunder methods #14659

@Gatsik

Description

@Gatsik

While their implementation even specifically checks whether operand is an instance of an Iterable (for example: https://github.com/python/cpython/blob/c779f2324df06563b4ba3d70d0941e619ccaf5ff/Lib/_collections_abc.py#L628)

from collections.abc import Set
from typing import Iterable, Iterator


class S[T](Set[T]):
    def __init__(self, s: Iterable[T] | None = None) -> None:
        super().__init__()
        self._set: set[T] = set(s) if s else set()

    def __contains__(self, value: object) -> bool:
        return value in self._set

    def __iter__(self) -> Iterator[T]:
        return iter(self._set)

    def __len__(self) -> int:
        return len(self._set)

    def add(self, value: T) -> None:
        self._set.add(value)

    def discard(self, value: T) -> None:
        self._set.discard(value)

    def __repr__(self) -> str:
        return self._set.__repr__()

s = S[int]((1,2,3))
print(s & [4])
print(s | ("4",))
print(s - [1])
print(s ^ ("1",))
$ mypy t.py

t.py:29: error: Unsupported operand types for & ("S[int]" and "list[int]")  [operator]
t.py:30: error: Unsupported operand types for | ("S[int]" and "tuple[str]")  [operator]
t.py:31: error: Unsupported operand types for - ("S[int]" and "list[int]")  [operator]
t.py:32: error: Unsupported operand types for ^ ("S[int]" and "tuple[str]")  [operator]
Found 4 errors in 1 file (checked 1 source file)
$ python3 t.py

set()
{1, 2, 3, '4'}
{2, 3}
{1, 2, 3, '1'}

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