python / python/typing

[spec] Formalize excluded Protocol members

Open
#1,833 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: documentation
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

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__.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the EXCLUDED_ATTRIBUTES definition in Lib/typing.py and compare it with PEP 544, the typing specification, and the linked pyright and mypy examples. Determine which Protocol members require formal specification and document the intended behavior so the differing checker results have a clear resolution.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.