[英]Typing dataclass that can only take enum values
I have a dataclass that can take values that are part of an enum.我有一个数据类,它可以采用作为枚举一部分的值。
class MyEnum(Enum):
A = "valueA"
B = "valueB"
@dataclass
class MyDataclass:
value: MyEnum
When creating my dataclass, the types don't match as it is considering str
!= MyEnum.A
.创建我的数据类时,类型不匹配,因为它正在考虑str
!= MyEnum.A
。
param = MyDataclass(value="valueA")
Any suggestion on how should MyDataclass
be typed instead?关于如何输入MyDataclass
的任何建议?
EDIT: The dataclass is being initialized with the string values I receive from another API编辑:数据类正在使用我从另一个 API 收到的字符串值进行初始化
Your class is typed correctly if you really want MyDataclass().value
to be a MyEnum
value.如果您真的希望MyDataclass().value
成为MyEnum
值,则您的类输入正确。 The problem is that you , as the person instantiating MyDataclass
, are responsible for actually passing a value of type MyEnum
to __init__
.问题是,作为实例化MyDataclass
的人,您负责将MyEnum
类型的值实际传递给__init__
。
If your use case requires a string to be passed, you'll have to handle the conversion yourself in __post_init__
, which does mean altering the class definition slightly.如果您的用例需要传递一个字符串,则您必须自己在__post_init__
中处理转换,这确实意味着稍微改变类定义。
from dataclasses import dataclass, InitVar, field
@dataclass
class MyDataclass:
value: MyEnum = field(init=False)
value_str: InitVar[str]
def __post_init__(self, value_str):
self.value = MyEnum(value_str)
Automatic conversion will require a different library, for example Pydantic or (I believe) attrs
;自动转换将需要不同的库,例如 Pydantic 或(我相信) attrs
; it's not a feature that dataclasses
supplies.这不是dataclasses
提供的功能。
The amount of static type protection this gives you is limited, because you are stating that any string can be passed as an argument to __init__
/ __post_init__
, but really only the ones that are valid arguments to MyEnum
are valid.这为您提供的静态类型保护的数量是有限的,因为您声明任何字符串都可以作为参数传递给__init__
/ __post_init__
,但实际上只有作为MyEnum
有效参数的字符串才有效。 This isn't really something that can be expressed using the typing
module, as Enum
itself isn't designed with static type checking in mind.这并不是真正可以使用typing
模块表达的东西,因为Enum
本身在设计时并没有考虑到静态类型检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.