Overzealous Optimization For `isinstance`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Bug report
Bug description:
The custom __instancecheck__ dunder method allows full customization (described in the Data model).
However, it produces a spurious result:
class CustomIsInstanceMeta(type):
def __instancecheck__(cls, instance: object) -> bool:
return type(instance) is int
class CustomIsInstance(metaclass=CustomIsInstanceMeta):
...
class CustomIsInstanceSubclass(CustomIsInstance):
...
print(isinstance(5, CustomIsInstance)) # True
print(isinstance(CustomIsInstance(), CustomIsInstance)) # True (should be False)
print(isinstance(CustomIsInstanceSubclass(), CustomIsInstance)) # False
This is caused by:
https://github.com/python/cpython/blob/23c488d6197191d355be6733699a295c20806932/Objects/abstract.c#L2641-L2644
which is invalid in this case.
This is a reframing of #79264 (request to fix documentation)
CPython versions tested on:
3.13
Operating systems tested on:
Linux
Linked PRs
- gh-144874
- gh-144997
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
Review Objects/abstract.c at lines 2641-2644 and the linked PRs gh-144874 and gh-144997. Run the supplied isinstance reproduction on Python 3.13/Linux to confirm the spurious results. Done means the reported behavior is resolved, with the outcome aligned with the documentation concern raised in #79264.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- c, python
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 25/100