__instancecheck__ metaclasses, how do they work: why do I get True when I tuple, why doesn't print run?

Veek M veek at dont-use-this.com
Mon Nov 4 06:30:42 EST 2019


1. Why do I get True whenever i tuple the 
isinstance(f, (Bar, Foo))
(and why don't the print's run)

The docs say that you can feed it a tuple and that the results are OR'd

----
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
-----
which implies that the metaclasses are called for each class?


class MyzMeta(type):
    def __instancecheck__(cls, other):
        print('MyzzzzzzMeta', other)
        return 0


class MyMeta(MyzMeta, object):
    def __instancecheck__(cls, other):
        print('MyMeta')
        print(cls, other)
        return 0

        
class Foo(list):
    __metaclass__ = MyzMeta
    pass

class Miaow(object):
    pass

class Bar(Foo, Miaow):
    __metaclass__ = MyMeta
    pass


f = Foo()
b = Bar()

print(isinstance(f, (Bar, Foo)))
raise SystemExit

if isinstance(f, (Bar, Foo)):
    print('success')


More information about the Python-list mailing list