2

I do something like this,

class MetaA(type):
  def __instancecheck__(self, obj):
    print('hello world')
    return super().__instancecheck__(obj)  
class A(metaclass=MetaA):
  pass
a = A()
isinstance(a, A)

gives,

True

whereas,

isinstance(None, A)

gives,

hello world
False

why did it not print hello world the first time?

when I create another class,

class C(A):
  pass

and then,

a = C()
isinstance(a, A)

gives,

hello world
True

but,

isinstance(a, C)

gives,

True

why does it not print hello world sometimes?

apostofes
  • 2,959
  • 5
  • 16
  • 31
  • Related: https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python/6581949#6581949. Most of the answers explain metaclass inheritance. – Codeman Mar 08 '22 at 13:13
  • ``type(a) is self`` holds for the cases that don't print. – MisterMiyagi Mar 08 '22 at 13:13
  • 1
    If it is an exact type match `__instancecheck__` won't be called, python circumvents the check – tgpz Mar 08 '22 at 13:21

0 Answers0