gh-153772: Make abc isinstance() tolerate instances without __class__#154149
Open
fedonman wants to merge 1 commit into
Open
gh-153772: Make abc isinstance() tolerate instances without __class__#154149fedonman wants to merge 1 commit into
fedonman wants to merge 1 commit into
Conversation
…lass__ The built-in isinstance() reads an instance's __class__ with a lookup that suppresses AttributeError and falls back to the object's type, so isinstance(obj, int) returns False for an object whose __class__ access raises. ABCMeta.__instancecheck__ read __class__ directly instead, so isinstance(obj, Mapping) leaked that AttributeError. Fall back to type(instance) when __class__ is unavailable, in both the C and the pure-Python implementations, so the abstract base classes behave like the built-in isinstance(). Such objects are unusual, but they do turn up in the wild (for example some Qt widgets).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The built-in
isinstance()reads an instance's__class__with a lookup that suppressesAttributeErrorand falls back to the object's type, so a value whose__class__access raises still checks cleanly:ABCMeta.__instancecheck__read__class__directly instead, so the same object leaked theAttributeErrorwhen checked against acollections.abcclass:This makes the abstract base class machinery fall back to
type(instance)when__class__is unavailable, in both the C (Modules/_abc.c) and the pure-Python (Lib/_py_abc.py) implementations, so it matches the built-inisinstance():>>> isinstance(NoClass(), Mapping) FalseObjects without a
__class__are unusual, but they do turn up in the wild (for example some Qt widgets, as noted in the issue).isinstancecheck againstcollection.abcclasses fails if value has no__class__#153772