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的深入解释.

推荐答案

您希望在这里使用枚举而不是数据类:

from enum import IntEnum

class MyEnum(IntEnum):
    A = 1
    B = 2

def foo(x: MyEnum):
    if (x == 1):
        return '1 given'
    else:
        return 'whatever'

foo(MyEnum.A) # Ok
foo(1)        # Error 
foo('pizza')  # Error

针对pyright和mypy类型判断器进行了测试(我不使用PyCharm,不确定它是在幕后运行还是JetBrains的某个自定义程序).

Python相关问答推荐

在Python中处理大量CSV文件中的数据

可变参数数量的重载类型(args或kwargs)

输出中带有南的亚麻神经网络

使用groupby Pandas的一些操作

PyQt5,如何使每个对象的 colored颜色 不同?'

Python+线程\TrocessPoolExecutor

在pandas中使用group_by,但有条件

创建可序列化数据模型的最佳方法

mypy无法推断类型参数.List和Iterable的区别

在嵌套span下的span中擦除信息

在代码执行后关闭ChromeDriver窗口

Python日志(log)模块如何在将消息发送到父日志(log)记录器之前向消息添加类实例变量

Python协议不兼容警告

如何防止html代码出现在quarto gfm报告中的pandas表之上

来自Airflow Connection的额外参数

随机森林n_估计器的计算

在一个数据帧中,我如何才能发现每个行号是否出现在一列列表中?

在聚合中使用python-polars时如何计算模式

函数()参数';代码';必须是代码而不是字符串

如何批量训练样本大小为奇数的神经网络?