python / python/cpython

Protocol named "Protocol" or "Generic" has no members.

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

还没有人认领这个 Issue。

stdlib topic-typing type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

If a protocol is named Protocol or Generic then it will ignore any defined members.

when you get lazy with naming in your unit tests this makes for quite a head scratcher...

Minimal Reproduction
import typing


class Protocol(typing.Protocol):
    a: int


members = typing.get_protocol_members(Protocol)

assert members == {"a"}, f"Expected members to be {{'a'}}, got {members}"
Output:
Traceback (most recent call last):
  File ".../test_protocol.py", line 10, in <module>
    assert members == {"a"}, f"Expected members to be {{'a'}}, got {members}"
           ^^^^^^^^^^^^^^^^
AssertionError: Expected members to be {'a'}, got frozenset()
Expected Output:

Nothing, script should succeed without error.

Investigation

The problem appears to stem from the _get_protocol_attrs function used by _ProtocolMeta which is defined as follows:

https://github.com/python/cpython/blob/171133aa84cd2fa8738bdbb0c76435645810e8d3/Lib/typing.py#L1879-L1899

The if statement on line 1887 is too loose in what it matches.

Possibile Fix

The check for base needs to be more specific, either using the instance itself:

if base in {Protocol, Generic}:
    continue

or checking the module too, in order to ensure its the correct class being excluded:

if base.__name__ in {'Protocol', 'Generic'} and base.__module__ == 'typing':
    continue
CPython versions tested on:

3.14

Operating systems tested on:

macOS

Linked PRs
  • gh-145724

贡献指南

打开贡献指南

从这里开始

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

调研方向

从报告中确定的函数 _get_protocol_attrs 所在的 Lib/typing.py 开始,并使用 Python 3.14 运行提供的最小复现。完成标准是:名为 Protocol 或 Generic 的用户定义类能够通过 typing.get_protocol_members 暴露其声明的协议成员;开始前请检查 gh-145724,因为该 issue 链接了一个现有的 pull request。

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

评估

技术栈
python
领域
backend
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
描述清楚
新手友好度
35/100

把新 issue 发到你的邮箱

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