Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python instanceof on alias type

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading