typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

set[str].discard(str | None)

Open Akuli opened this issue 3 years ago • 3 comments
trafficstars

Consider the following:

names: set[str] = {"a", "b"}
name: str | None = None
names.discard(name)

It would be nice if this wasn't a type checker error. Unlike .remove(), the .discard() method does nothing if the item is not in the set, so I don't see a good reason to ban None values.

Akuli avatar Feb 03 '22 09:02 Akuli

Related: #7015, #6597

Akuli avatar Feb 03 '22 09:02 Akuli

I agree, though we can't use object as the annotation -- it would have to be Any:

>>> s = {1, 2}
>>> s.discard([])
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    s.discard([])
TypeError: unhashable type: 'list'

AlexWaygood avatar Feb 08 '22 12:02 AlexWaygood

Would the Hashable type be able to be used here, as None is able to be hashed:

In [1]: hash(None)
Out[1]: 271809023

kkirsche avatar Aug 18 '22 13:08 kkirsche