Type hints for Type[dataclass] is not working in Pycharm

Viewed 30

Please check the following simple code.

@dataclass
class FooData:
    bar: int
    baz: str
    

FooData(1, 's')  # works fine


def through() -> Type[FooData]:
    return FooData


DataClass = through()
DataClass(1, 's')  # warning, unexpected arguments

Type hint for the function or method with return Type[Dataclass] is not working.

Is it a PyCharm bug or am I doing something wrong?

Pycharm version: PyCharm 2021.3.3 (Professional Edition)

1 Answers

Seems to be a problem with the way PyCharm handles the decorator. I have the same issue. Doing the same thing, but also specifying the __init__ method accordingly makes it behave as expected.

I would suggest using of Pydantic models instead. They do the same thing, are handled properly and provide a bunch of nice additional features, including but not limited to automatic validation. The only difference is that they require you to initialize using keyword-arguments.

Here is an example.

from pydantic import BaseModel
from typing import Type


class FooData(BaseModel):
    bar: int
    baz: str


FooData(bar=1, baz='s')  # works fine


def through() -> Type[FooData]:
    return FooData


Model = through()
Model(bar=1, baz='s')  # also works fine

Other than that, this warrants a ticket in the JetBrains Issue Tracker.

Related