gpt4 book ai didi

python - 重用数据类类型提示

转载 作者:行者123 更新时间:2023-12-04 17:20:08 25 4
gpt4 key购买 nike

我正在尝试在我的函数签名中重用来自数据类的类型提示 - 也就是说,不必再次输入签名。
解决这个问题的最佳方法是什么?

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)

最佳答案

What would be the best way of going about this?


PEP 484 为这种情况提供了一个明确的选择

Type aliases

Type aliases are defined by simple variable assignments:(...)Type aliases may be as complex as type hints in annotations -- anything that is acceptable as a type hint is acceptable in a type alias:


应用于您的示例,这将等于(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)
以上是使用 Python 3.9 以后编写的 Generic Alias Type .自 typing.Set 以来,语法更加简洁和现代和 typing.Tuple已被弃用。

现在,从 Python Data Model 的角度完全理解这一点比看起来更复杂:

3.1. Objects, values and types

Every object has an identity, a type and a value.


您第一次尝试使用 Type会产生惊人的结果
>>> type(MyDataClass.force)

AttributeError: type object 'MyDataClass' has no attribute 'force'
这是因为内置函数 type返回一个类型(它本身就是一个对象)但是 MyDataClass是“类”(声明)和“类属性” force是在类上而不是在类的类型对象上,其中 type()寻找它。仔细注意数据模型的区别:
  • Classes

    These objects normally act as factories for new instances of themselves

  • Class Instances

    Instances of arbitrary classes


相反,如果您检查实例上的类型,则会得到以下结果
>>> 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__ 在 Class 声明对象上(这里我们看到前面提到的 Generic Alias type)。 (这里我们确实检查了类属性 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]]}

I've had to write the same type annotation in the dataclass and the function signature -


对于元组,注释往往会变成长文字,这证明创建一个目的变量是为了简洁。但总的来说,显式签名更具描述性,这也是大多数 API 所追求的。

The typing Module

Fundamental building blocks:

Tuple, used by listing the element types, for example Tuple[int, int, str]. The empty tuple can be typed as Tuple[()]. Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis, for example Tuple[int, ...]. (The ... here are part of the syntax, a literal ellipsis.)

关于python - 重用数据类类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66681953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com