Add typing.get_protocol_members and typing.is_protocol · Issue #104873 · python/cpython (original) (raw)

#103160 added an attribute __protocol_attrs__ that holds the names of all protocol attributes:

>>> from typing import Protocol
>>> class X(Protocol):
...     a: int
...     def b(self) -> str: pass
... 
>>> X.__protocol_attrs__
{'b', 'a'}

This is useful for code that needs to extract the names included in a Protocol at runtime. Previously, this was quite difficult, as you had to look at the class's __dict__ and __annotations__ directly and exclude a long list of internal attributes (e.g. https://github.com/quora/pyanalyze/blob/bd7f520adc2d8b098be657dfa514d1433bea3b0c/pyanalyze/checker.py#L428).

However, currently __protocol_attrs__ is an undocumented private attribute. I think we should either document it or add an introspection helper like typing.get_protocol_attrs() that exposes it.

Linked PRs