1

Take the following code:

class MyMeta(type):

    def __instancecheck__(cls, instance):
        print('Checking instance')
        return True

class MyClass(object):
    __metaclass__ = MyMeta

print(isinstance(1, MyClass))

In Python 2.7, the output is

checking instance
True

In Python 3.5, the output is

False

This implies the __instancecheck__ of MyMeta is being used in Python 2 but not in Python 3 for whatever reason. The section on __isinstance__ is the same in the Python 2 and 3 docs, and I haven't been able to find the cause of this difference of behavior. Anyone know why?

Jeremy McGibbon
  • 3,527
  • 14
  • 22
  • 1
    How did you define `MyClass` in python 3? The `__metaclass__ = ...` syntax only works in python 2. – Aran-Fey Apr 04 '18 at 16:03
  • @Aran-Fey you've got at the answer to the question probably, I used the same code in both. – Jeremy McGibbon Apr 04 '18 at 16:09
  • The metaclass’s instance check is being called both times, but in 3.x, the metaclass isn’t `MyMeta`, it’s `type`. So that’s why the docs on `__instancecheck__` don’t explain the difference—because the difference is somewhere else, in how you specify a metaclass. – abarnert Apr 04 '18 at 16:09
  • Thanks @vaultah and @abarnert! – Jeremy McGibbon Apr 04 '18 at 16:10

0 Answers0