fis*_*x44 8 python alias python-3.x mypy python-typing
我试图在函数签名中重用数据类中的类型提示 - 也就是说,无需再次输入签名。
解决这个问题的最佳方法是什么?
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)
Run Code Online (Sandbox Code Playgroud)
解决这个问题的最佳方法是什么?
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)
Run Code Online (Sandbox Code Playgroud)
以上是使用 Python 3.9 及以上的Generic Alias Type编写的。由于typing.Set和typing.Tuple已被弃用,因此语法更加简洁和现代。
现在,从Python 数据模型的角度充分理解这一点比看起来更复杂:
每个对象都有一个身份、类型和值。
您的第一次尝试Type将会产生惊人的结果
>>> type(MyDataClass.force)
AttributeError: type object 'MyDataClass' has no attribute 'force'
Run Code Online (Sandbox Code Playgroud)
这是因为内置函数type返回一个类型(它本身就是一个对象),但MyDataClass它是“类”(声明),并且“类属性”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'>
Run Code Online (Sandbox Code Playgroud)
现在让我们通过force应用于类声明对象(这里我们看到前面提到的通用别名类型)来恢复类型对象(不是类型提示)。(这里我们确实在类属性上检查类型对象)。type()__anotations__force
>>> type(MyDataClass.__annotations__['force'])
<class 'typing._GenericAlias'>
Run Code Online (Sandbox Code Playgroud)
或者我们可以检查类实例上的注释,并恢复我们习惯看到的类型提示。
>>> init_values: set = {(True, "the_str", 1.2)}
>>> a_var = MyDataClass(init_values)
>>> a_var.__annotations__
{'force': set[tuple[str, float, bool]]}
Run Code Online (Sandbox Code Playgroud)
我必须在数据类和函数签名中编写相同的类型注释 -
对于元组,注释往往会变成很长的文字,这证明了为了简洁而创建目的变量是合理的。但一般来说,显式签名更具描述性,这也是大多数 API 所追求的。
基本构建块:
元组,通过列出元素类型来使用,例如
Tuple[int, int, str]。空元组可以键入为Tuple[()]。例如,可以使用一种类型和省略号来表示任意长度的同质元组Tuple[int, ...]。(...here 是语法的一部分,是字面省略号。)