Jim's answer seems to nail it.
But for whoever needs for some weid reason a fully customized
instancheck (ok, now that I am writing this, there seems to be
no correct reason for one to want that, let s hope I am wrong), a metaclass can get
away with it, but it is tricky.
This one dynamically replaces the actual class
of the object being instantiated by a "shadow class", that
is a clone of the original. This way, the native "instancheck" always
fail, and the metaclass one is called.
def sub__new__(cls, *args, **kw):
metacls = cls.__class__
new_cls = metacls(cls.__name__, cls.__bases__, dict(cls.__dict__), clonning=cls)
return new_cls(*args, **kw)
class M(type):
shadows = {}
rev_shadows = {}
def __new__(metacls, name, bases, namespace, **kwd):
clonning = kwd.pop("clonning", None)
if not clonning:
cls = super().__new__(metacls, name, bases, namespace)
# Assumes classes don't have a `__new__` of them own.
# if they do, it is needed to wrap it.
cls.__new__ = sub__new__
else:
cls = clonning
if cls not in metacls.shadows:
clone = super().__new__(metacls, name, bases, namespace)
# The same - replace for unwrapped new.
del clone.__new__
metacls.shadows[cls] = clone
metacls.rev_shadows[clone] = cls
return metacls.shadows[cls]
return cls
def __setattr__(cls, attr, value):
# Keep class attributes in sync with shadoclass
# This could be done with 'super', but we'd need a thread lock
# and check for re-entering.
type.__setattr__(cls, attr, value)
metacls = type(cls)
if cls in metacls.shadows:
type.__setattr__(metacls.shadows[cls], attr, value)
elif cls in metacls.rev_shadows:
type.__setattr__(metacls.rev_shadows[cls], attr, value)
def call(cls, *args, **kw):
# When __new__ don't return an instance of its class,
# __init__ is not called by type's __call__
instance = cls.__new__(*args, **kw)
instance.__init__(*args, **kw)
return instance
def __instancecheck__(cls, other):
print("doing instance check")
print(cls)
print(other)
return False
class A(metaclass=M):
pass
print(type(A))
print(isinstance(A(), A))
It even has a mechanism do sync attributes in the shadow class and actual class. The one thing it does not support is if classes handled in this way do implement a custom __new__
. If such a __new__
makes use of parameterless super
, it starts to become tricky, as the parameter to super would not be the shadow class.