简体   繁体   中英

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM