I have the following types and type alias defined:
@unique
class MyEnum(Enum):
A = 1
B = 2
C = 3
D = 4
class A:
pass
class B:
pass
MyAlias = MyEnum | A | B
MyAlias2 = MyAlias | str | int
@dataclass(slots=True)
class A:
type: MyAlias2
If I do isinstance check like so:
a = A()
isintance(a, MyAlias)
it returns False.
I understand that it happens because I redefine the class later, but I do this because I first need to define what is a type of type MyAlias so I could later define what is MyAlias2 to then be able to use it as an attribute inside class A. Now obviously since we’re in python I could just not define the attributes of class A and make a constructor that accept whatever, but since I’m thinking about portability in the future, and also I do want the "benefits" of type hinting right now, I do it this way and I wonder what can I do to make the isinstance report True in such case where there’s circular dependency between what is defined first.
>Solution :
You can define A first and use a string as the typehint.
@dataclass(slots=True)
class A:
type: 'MyAlias'
MyAlias = MyEnum | A | B