Create alias of class with different properties (e.g. docs) but passing all cross `isinstance` checks

38 Views Asked by At

I have a class and want to create an alias for it. However, I want all instances of the alias class to pass the instance check with the original and alias class, and the same for all instances of the original class. Is that possible in python?

I tried the following (after some edits with comments) but it doesnt work.

from abc import ABC

class ParentClass(ABC):
    """Abstract base class"""

class MetaClass(type):
    def __instancecheck__(cls, instance):
        return isinstance(instance, cls) or isinstance(instance, AliasClass)

class OGClass(ParentClass, metaclass=MetaClass):
    """OGClass docs"""
    def __init__(self):
        self.property1 = "property1"

class AliasClass(OGClass):
    """other doc"""

og_obj = OGClass()
ali_obj = AliasClass()

assert isinstance(og_obj, OGClass)    # True
assert isinstance(ali_obj, OGClass)   # True
assert isinstance(ali_obj, AliasClass)# True
assert isinstance(og_obj, AliasClass) # False, I want this to be True

Moreover it is important that both classes have separate doc strings, so I need

assert OGClass.__doc__ == """OGClass docs""" # True
assert AliasClass.__doc__ == """other doc""" # True

Is that possible without doing something sketchy like setting self.__class__ = AliasClass in the __init__ of OGClass (this works but I guess is not recommended?)

0

There are 0 best solutions below