How to support dynamic type hint in self code?

from dataclasses import dataclass

class Test:
a: int = 0

def mydataclass(cls):
setattr(cls, "__init__", make_init())
return cls

def make_init():
locals = {}
txt = f'def __init__(self, a: int = 1):\n pass'
exec(txt, None, locals)
return locals['__init__']

class MyTest:

if __name__ == '__main__':
Test(a='a') # Expected type 'int', got 'str' instead
MyTest(a='a') # There is none type hint
Comment actions Permalink


The first case is correct. The second one (metaprogramming) is mostly not supported by PyCharm.

Comment actions Permalink

The second one uses the same implement as the first code to make the `__init__` funcion dynamic, how it can get the proper type hinting.

Comment actions Permalink

Type hinting is well described in our documentation
Though, like I said, PyCharm doesn't understand metaprogramming mostly.

Comment actions Permalink

The first one is using the metaprogramming, but PyCharm understand it. I want to know what should I do to let PyCharm understand it.

Comment actions Permalink

PyCharm understands @dataclass decorator, but doesn't understand your custom decorator @mydataclass. You could use @dataclass for MyTest and change it to be similar to Test.

If it is required to have custom decorators this way, then the only option is to write some plugin for PyCharm.


Please sign in to leave a comment.