I have identified several methods on built-in types that are too strict and can cause annoying false positives:
It seems like the annotations for these were designed to help detect user errors. For instance, we know that .get on a dict[int, int] will always return the default as the types are incompatible, and so .get was restricted in typeshed to only accept the key type. However, this hurts, even in simple cases like using literals:
from typing import Mapping, Literal
def demo_get(
d: Mapping[Literal["foo", "bar"], int],
dynamic_key: str,
) -> None:
# No overload variant of "get" of "Mapping" matches argument type "str"
d.get(dynamic_key)
def demo_sub(
left: set[Literal["foo", "bar"]],
right: set[str],
) -> None:
# Unsupported operand types for - ("set[Literal['foo', 'bar']]" and "set[str]")
left - right
I believe typeshed is trying to act as a linter here, which shouldn't be its job. Type-checkers and type-informed linters are better at this and can use more complex logic.
For example, in the set difference case set[A] - set[B], the proper test would be to check whether the types have a non-empty intersection or not. The same could be said for Mapping[K, V].get(K2).
Related Topics:
I have identified several methods on built-in types that are too strict and can cause annoying false positives:
dict.{get, pop}(allow object type in dict.get and dict.pop #15471)list.{count, index, remove}(Update list.{count, index, remove} to acceptobjecttype #15472)MutableSet.discardMapping.getMutableMapping.popSequence.{count, index}MutableSequence.removeIt seems like the annotations for these were designed to help detect user errors. For instance, we know that
.geton adict[int, int]will always return the default as the types are incompatible, and so.getwas restricted in typeshed to only accept the key type. However, this hurts, even in simple cases like using literals:I believe typeshed is trying to act as a linter here, which shouldn't be its job. Type-checkers and type-informed linters are better at this and can use more complex logic.
For example, in the set difference case
set[A] - set[B], the proper test would be to check whether the types have a non-empty intersection or not. The same could be said forMapping[K, V].get(K2).Related Topics:
Mapping.__contains__expectsobject, butMapping.getexpects a strict type? #8219dict.getoverload with default value not be generic? #9155set.__sub__and related methods are inconsistent #9004