python类型提示数据级属性的注释
我有一个dataclass
,我将其用作常数存储。
@dataclass
class MyClass:
CONSTANT_1 = "first"
CONSTANT_2 = "second"
我有一个函数:
def my_func(value: ?):
print(value)
我想向我的功能添加注释,以指定可能的 value 是 myclass
如何做的属性之一(我使用的是Python 3.10)?
I have a dataclass
and I use it as a constant store.
@dataclass
class MyClass:
CONSTANT_1 = "first"
CONSTANT_2 = "second"
I have a function:
def my_func(value: ?):
print(value)
I want to add annotation to my function to specify that possible value is one of attribute of MyClass
How to do it (I am using python 3.10) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
希望我不要误解问问,请告诉我是否这样。但是我认为在这种情况下,最好使用
enum a>类型为Python。
这是一个简单的示例:
然后回答第二部分,为注释
?
变成myenum
。这意味着这种类型的任何枚举成员,而不是类型(类)本身。将所有这些放在一起,就像:
Hopefully I not misunderstand the ask, please let me know if so. But I think in this case is best to use
Enum
type in python.Here is a simple example:
Then to answer the second part, for annotation the
?
becomes aMyEnum
. This means any enum member of this type, but not the type (class) itself.Putting it all together, it becomes like:
我想您在问一个 xy问题。从您的评论中的响应来看,您似乎想要的是:
如rv.kvetch的答案,常规的做法是使用枚举。我不确定您的意思是“想跳过
.value
”,value
枚举字段只是为您提供了与该枚举相关的内容,我会说这一点都不重要。以下是一个示例:我想与此示例显示的是两件事:
value
。enum.auto()
自动分配其唯一值。因为归根结底,枚举本身已经代表了有效选择之间的选择,因此它具有什么价值都没关系。
也就是说,如果您想要的只是对参数可以键入的值进行类型限制,而不必使用枚举,那么您可以使用
文字
类型。参见此答案细节。就您的示例而言,您可以做类似的事情:但是请注意,类型的注释并不能真正阻止您调用具有无效值的函数,这只是IDE和类型检查器的提示。
I think you're asking an XY problem. From your response in the comments, it seems like what you want is rather:
As as mentioned in rv.kvetch's answer, the conventional way of doing this is to use enums. I'm not sure what you mean by "wanting to skip
.value
", thevalue
field of an enum simply gives you what's associated with that enum, and I would say that it's not important at all. Here's an example:What I want to show with this example are two things:
.value
at all if you're just comparing enums.enum.auto()
to auto-assign a unique value to it.Because at the end of the day, enums themselves already represent a choice among valid choices, so it doesn't matter what values it has.
That said, if what you want is just to put a type constraint on what values an argument can type, and not have to use enums, then you can use the
Literal
type. See this answer for details. For your example, you could do something like:But note that type annotations don't really prevent you from calling a function with an invalid value, it's just a hint for IDEs and type checkers.