`typing`: one `None`-valued member makes `isinstance()` on a `runtime_checkable` Protocol O(N) per call
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
A class satisfying a @runtime_checkable Protocol with any class attribute set to None still passes isinstance(), but is orders of magnitude slower, scaling linearly with member count. Best of 5 runs of 20,000 calls, at 5/20/50/110 members: 25x/84x/316x/735x slower.
import timeit
from typing import Protocol, runtime_checkable
@runtime_checkable
class P(Protocol):
@property
def a(self) -> bool: ...
@property
def b(self) -> bool: ...
class Good:
a = b = True
class Bad:
a, b = True, None
for x in (Good(), Bad()):
print(isinstance(x, P), timeit.timeit(lambda: isinstance(x, P), number=100_000))
On 3.13.13: True 0.0121 then True 0.1207. Only the timing differs.
Linked PRs
- gh-156451
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the minimal Protocol/runtime_checkable reproduction in the issue and compare the timing for Good and Bad across member counts. Review the linked PR gh-156451 and the typing implementation it changes; done means the None-valued case no longer causes linear-time isinstance() checks while preserving the reported True results.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100