python / python/typeshed

Is there a good reason why `Mapping.__contains__` expects `object`, but `Mapping.get` expects a strict type?

Abierto
#8,219 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

stubs: false negative
Lenguaje dominante
Python
Estrellas
5.1k
Forks
2.1k
Merge medio
1 d 19 h
PR fusionados (30 d)
82

Descripción

I ran into a case where a user intended to check whether an enum value x was present in a dictionary Dict[int, int]: x.value in d.

But instead they wrote x in d, which always fails, since the Enum itself is never a key in the dictionary. The type checker didn't complain since the typeshed stub for Mapping.__contains__ accepts any type compatible with object:

    def __contains__(self, __o: object) -> bool: ...

However, if the user had used d.get(x), the type checker would have complained, because the typeshed stub for Mapping.get is stricter:

    def get(self, __key: _KT) -> _VT_co | None: ...

Simple repro:

d: dict[int, int] = {1: 2}

# no type error
'hello' in d

# type error
d.get('hello')

It looks like the stub for __contains__ has expected object ever since typing.pyi was added to typeshed (in 2015). If the idea is that users may want to check for existence of keys of arbitrary types, a similar argument would hold for d.get(x).

Is there a good reason why the stub complains about d.get(x) but not x in d? Otherwise, it'd be good to make __contains__ stricter.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Read the Mapping.contains and Mapping.get stubs in typing.pyi, starting with the historical object annotation for contains. Reproduce the issue with the Dict[int, int] examples, then determine whether the annotations should be made consistent; done means the decision is documented in the issue and the relevant stub reflects it if a change is warranted.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
tooling
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
38/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.