Python:如何键入提示数据类?

Mr.*_* B. 2 python python-dataclasses python-typing

下面的代码有效,但我收到 PyCharm 的以下警告:

在“(...) -> Any”中找不到参考__annotations__

我想这是因为我正在使用Callable. 我没有找到类似的东西Dataclass。我应该使用哪种类型?

from __future__ import annotations
from dataclasses import dataclass
from typing import Callable

@dataclass
class Fruit:
  color: str
  taste: str

def get_cls() -> Callable:
  return Fruit

attrs = get_cls().__annotations__  # <- IDE warning
print(attrs)
Run Code Online (Sandbox Code Playgroud)

2e0*_*byo 5

在这个特定的例子中,你可以直接提示它:

from dataclasses import dataclass

@dataclass
class Fruit:
    x: str

def get_cls() -> type[Fruit]:
    return Fruit

attrs = get_cls().__annotations__
print(attrs)
Run Code Online (Sandbox Code Playgroud)
$ python d.py
{'x': <class 'str'>}
$ mypy d.py
Success: no issues found in 1 source file
Run Code Online (Sandbox Code Playgroud)

不过我不知道你问的是不是这个。您是否正在寻找任何数据类的泛型类型?(我很想暗示所有可能的返回类型的并集get_cls():使用数据类而不是字典的全部意义肯定是区分数据类型。如果您尝试,您确实希望类型检查器警告您访问未在数据类之一上定义的属性。)

参考

请参阅现在可用的文档typing.Typetype(就像我们现在可以使用listanddict而不是typing.Listand一样typing.Dict)。