我试图在函数签名中重用来自dataclass的类型提示--也就是说,不必再次键入签名。
做这件事最好的方法是什么?
from dataclasses import dataclass
from typing import Set, Tuple, Type
@dataclass
class MyDataClass:
force: Set[Tuple[str, float, bool]]
# I've had to write the same type annotation in the dataclass and the
# function signature - yuck
def do_something(force: Set[Tuple[str, float, bool]]):
print(force)
# I want to do something like this, where I reference the type annotation from
# the dataclass. But, doing it this way, pycharm thinks `force` is type `Any`
def do_something_2(force: Type["MyDataClass.force"]):
print(force)发布于 2021-03-28 18:12:00
做这件事最好的方法是什么?
PEP 484为这种情况提供了一个明确的选项。
类型别名 类型别名由简单的变量赋值定义:(.)类型别名可能与注释中的类型提示一样复杂--在类型别名中,任何可以接受的类型提示都是可以接受的:
应用于您的示例,这将相当于(Mypy确认这是正确的)
from dataclasses import dataclass
Your_Type = set[tuple[str, float, bool]]
@dataclass
class MyDataClass:
force: Your_Type
def do_something(force: Your_Type):
print(force)上面的内容是使用Python3.9继续编写的属别名类型。自从typing.Set和typing.Tuple被废弃以来,语法更加简洁和现代。
现在,从Python数据模型的角度来充分理解这一点比看起来要复杂得多:
3.1。对象、值和类型 每个对象都有一个标识、一个类型和一个值。
你第一次尝试使用Type会产生一个惊人的结果
>>> type(MyDataClass.force)
AttributeError: type object 'MyDataClass' has no attribute 'force'这是因为内置函数type返回一个类型(它本身就是一个对象),但是MyDataClass是“一个类”(一个声明),而"Class属性“force在类上,而不是在type()查找它的类的类型对象上。请注意数据模型中的差异:
如果您检查了实例上的类型,则会得到以下结果
>>> init_values: set = {(True, "the_str", 1.2)}
>>> a_var = MyDataClass(init_values)
>>> type(a_var)
<class '__main__.MyDataClass'>
>>> type(a_var.force)
<class 'set'>现在让我们通过将force上的type()应用于类声明对象上的__anotations__ (在这里我们看到前面提到的属别名类型 )来恢复__anotations__上的类型对象(而不是类型提示)。(在这里,我们确实在检查类属性force上的类型对象)。
>>> type(MyDataClass.__annotations__['force'])
<class 'typing._GenericAlias'>或者,我们可以检查Class实例上的注释,并恢复类型提示,因为我们习惯于看到它们。
>>> init_values: set = {(True, "the_str", 1.2)}
>>> a_var = MyDataClass(init_values)
>>> a_var.__annotations__
{'force': set[tuple[str, float, bool]]}我必须在dataclass和函数签名中写相同类型的注释-
对于元组,注释往往会变成长文本,这就有理由为简洁创建一个目的变量。但是一般来说,显式签名更具有描述性,这也是大多数API所追求的。
模块 基本积木: 元组,用于列出元素类型,例如
Tuple[int, int, str]。空元组可以键入为Tuple[()]。任意长度的齐次元组可以使用一种类型和省略号表示,例如Tuple[int, ...].(那个.这里是语法的一部分,文字省略。)
https://stackoverflow.com/questions/66681953
复制相似问题