I've a frozen dataclass with some constants and function, which accept any constant from this class as it's argument.
How can I typehint this mechanic? I need to tell user that function waits for any field's value from this specific dataclass.
It should looks like this:
from dataclasses import dataclass
@dataclass(frozen=True)
class Consts:
const_0: int = 0
const_1: int = 1
const_2: int = 2
const_3: int = 3
def foo(param: Consts.field):
return param
UPD:
According to @JaredSmith hint I've tried to use Enum. It look like much correct. But the problem still exists.
I've tried to use typing.Literal
, like this:
def foo(param: Literal[Consts.const_0, Consts.const_1]):
return param
但它不会给出正确的类型提示.在情况foo(Consts)
中,我们将得到这样的警告:Expected type 'Consts', got 'Type[Consts]' instead
,而不是类似的东西:Expected type Consts.value got Consts instead
因此,更新后的主要问题是:如何在代码中聚合逻辑组中的常量以简化它们的使用(数据类或枚举),以及如何键入相应的解决方案.
一百: 非常感谢所有的 comments .他们向我展示了许多有趣的事实.作为当前问题的答案,我 Select @JaredSmith的IntEnum变体.此外,感谢@chepner和@InSync的深入解释.