Resolved: How to typehint dynamic class instantiation like pydantic and dataclass?

In this post, we will see how to resolve How to typehint dynamic class instantiation like pydantic and dataclass?

Question:

Both Pydantic and Dataclass can typehint the object creation based on the attributes and their typings, like these examples:
With this code, I can get typehint on object creation (see screenshots below):
pydantic typehint on object creation
dataclass typehint on object creation
Not only that, but the object’s attributes also get documented.
I studied the code of pydantic to try to achieve the same result, but I couldn’t. The code that I tried was this:
My class works (the dynamic init insertion works) but the class and object get no typehint.
my class works but it doesn’t get typehinted
What am I doing wrong? How can I achieve the typehints?

Best Answer:

@chepner is right.

Static type checkers don’t execute your code, they just read it.


And to answer your question how Pydantic and dataclasses do it – they cheat:

Special plugins allow mypy to infer the signatures that are actually only created at runtime. (I am just joking about the “cheating” of course, but you get my point.)
If you want your own dynamic annotations to be considered by static type checkers, you will have to write your own plugins for them.

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com