python / python/typeshed

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

Ouverte
#8,219 2 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

stubs: false negative
Langage dominant
Python
Étoiles
5.1k
Forks
2.1k
Merge moyen
1 j 19 h
PR mergées (30 j)
82

Description

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.

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

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.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
python
Domaine
tooling
Type d'issue
Bug
Difficulté
4/5
Temps estimé
3-5 jours
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
38/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.