Make isinstance(OldstyleClass, NewstyleClass) return False instead of raising

an exception. Issue reported by Joseph Armbruster.
This commit is contained in:
Jeffrey Yasskin 2008-03-17 16:31:21 +00:00
parent 1b4e45bab9
commit b9e15f7555
2 changed files with 16 additions and 5 deletions

View File

@ -116,18 +116,18 @@ class ABCMeta(type):
def __instancecheck__(cls, instance):
"""Override for isinstance(instance, cls)."""
# Inline the cache checking for new-style classes.
subclass = instance.__class__
# Inline the cache checking when it's simple.
subclass = getattr(instance, '__class__', None)
if subclass in cls._abc_cache:
return True
subtype = type(instance)
if subtype is subclass:
if subtype is subclass or subclass is None:
if (cls._abc_negative_cache_version ==
ABCMeta._abc_invalidation_counter and
subclass in cls._abc_negative_cache):
subtype in cls._abc_negative_cache):
return False
# Fall back to the subclass check.
return cls.__subclasscheck__(subclass)
return cls.__subclasscheck__(subtype)
return (cls.__subclasscheck__(subclass) or
cls.__subclasscheck__(subtype))

View File

@ -70,6 +70,17 @@ class TestABC(unittest.TestCase):
self.assertFalse(issubclass(OldstyleClass, A))
self.assertFalse(issubclass(A, OldstyleClass))
def test_isinstance_class(self):
class A:
__metaclass__ = abc.ABCMeta
class OldstyleClass:
pass
self.assertFalse(isinstance(OldstyleClass, A))
self.assertTrue(isinstance(OldstyleClass, type(OldstyleClass)))
self.assertFalse(isinstance(A, OldstyleClass))
# This raises a recursion depth error, but is low-priority:
# self.assertTrue(isinstance(A, abc.ABCMeta))
def test_registration_basics(self):
class A:
__metaclass__ = abc.ABCMeta