输入只能采用枚举值的数据类
我有一个数据级,可以采用枚举的值。
class MyEnum(Enum):
A = "valueA"
B = "valueB"
@dataclass
class MyDataclass:
value: MyEnum
创建我的数据级时,类型不匹配,因为它正在考虑str
!= myenum.a
。
param = MyDataclass(value="valueA")
关于MyDataClass
应该如何键入的任何建议?
编辑:Dataclass正在用我从另一个API收到的字符串值初始化
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
.
param = MyDataclass(value="valueA")
Any suggestion on how should MyDataclass
be typed instead?
EDIT: The dataclass is being initialized with the string values I receive from another API
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您真的想要
myDataClass()。值
是myenum
value,则您的类是 正确的。问题是 you ,作为实例化myDataClass
的人,负责实际将类型myenum
的值传递给________________ init __ init __ init __ 。
如果您的用例需要通过一个字符串,则必须在
__ post_init __
中自己处理转换,这确实意味着稍微更改类定义。自动转换将需要不同的库,例如pydantic或(我相信)
attrs
;这不是dataclasses
供应的功能。这给您的静态类型保护的量是有限的,因为您指出任何 string可以作为参数传递给
__ init __ init __ init __
/__ post_init __init __
,但实际上只有有效论证myenum
有效的那些是有效的。这并不是可以使用键入
模块来表达的东西,因为enum
本身并非考虑到静态类型检查。Your class is typed correctly if you really want
MyDataclass().value
to be aMyEnum
value. The problem is that you, as the person instantiatingMyDataclass
, are responsible for actually passing a value of typeMyEnum
to__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.Automatic conversion will require a different library, for example Pydantic or (I believe)
attrs
; it's not a feature thatdataclasses
supplies.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 toMyEnum
are valid. This isn't really something that can be expressed using thetyping
module, asEnum
itself isn't designed with static type checking in mind.您可以这样做:
类肌电(枚举):
答:str =“ inlive”
B:str =“ prelive”
you can do it this way:
class MyEnum(Enum):
A: str = "INLIVE"
B: str = "PRELIVE"