python / python/typeshed

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

未关闭
#8,219 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stubs: false negative
主要语言
Python
星标
5.1k
派生
2.1k
平均合并
1 天 19 小时
30 天内合并 PR
82

描述

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.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

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.

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
tooling
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
38/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。