How to support dynamic type hint in self code?

Answered
from dataclasses import dataclass

@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__']


@mydataclass
class MyTest:
pass


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

Hi,

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

0

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.

0

Type hinting is well described in our documentation https://www.jetbrains.com/help/pycharm/type-hinting-in-product.html
Though, like I said, PyCharm doesn't understand metaprogramming mostly.

0

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

0

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.

0

Please sign in to leave a comment.