python / python/typing

[spec] Formalize excluded Protocol members

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

还没有人认领这个 Issue。

topic: documentation
主要语言
Python
星标
1.8k
派生
302
平均合并
23 小时
30 天内合并 PR
8

描述

At runtime, the following members are currently excluded by Protocol: (source)

_TYPING_INTERNALS = frozenset({
    '__parameters__', '__orig_bases__',  '__orig_class__',
    '_is_protocol', '_is_runtime_protocol', '__protocol_attrs__',
    '__non_callable_proto_members__', '__type_params__',
})


_SPECIAL_NAMES = frozenset({
    '__abstractmethods__', '__annotations__', '__dict__', '__doc__',
    '__init__', '__module__', '__new__', '__slots__',
    '__subclasshook__', '__weakref__', '__class_getitem__',
    '__match_args__', '__static_attributes__', '__firstlineno__',
    '__annotate__',
})


# These special attributes will be not collected as protocol members.
EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS | _SPECIAL_NAMES | {'_MutableMapping__marker'}

However, neither PEP 544 nor the typing spec formalize this list, which leads to diverging behavior between different type checkers:

Code sample in pyright playground, mypy playground

from typing import TypeIs, Protocol

class MyProtocol(Protocol):
    @classmethod
    def __subclasshook__(cls, other: type, /) -> TypeIs[type["MyProtocol"]]:
        ...

x: MyProtocol = int(1)  # mypy: ✅ pyright: ❌

Code sample in pyright playground, mypy playground

from typing import Protocol

class MyProtocol(Protocol):
    __abstractmethods__: frozenset[str]
    
x: MyProtocol = int(1)  # mypy: ✅ pyright: ❌

A real-world example where this matters is for instance a Protocol for NamedTuple Instances, that checks whether types.get_original_bases(cls) includes typing.NamedTuple inside __subclasshook__.

贡献指南

这个仓库没有索引到贡献指南

从这里开始

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

调研方向

从 Lib/typing.py 中的 EXCLUDED_ATTRIBUTES 定义开始,将其与 PEP 544、typing specification 以及链接的 pyright 和 mypy 示例进行比较。确定哪些 Protocol 成员需要正式规范,并记录预期行为,以便对 checker 产生的不同结果给出明确的解决方案。

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

评估

技术栈
python
领域
documentation
Issue 类型
文档
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

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