Python 类型提示:如何进行文字范围

Stu*_*ent 5 python literals type-hinting pydantic

我使用 pydantic 的类型提示来设置 Python API 的返回架构。

我想编写一个允许数字 0 到 100 的文字类型。手动输入很容易:

from typing import Literal
MyType = Literal[0, 1, 2, ... , 99, 100]
Run Code Online (Sandbox Code Playgroud)

这不是特别Pythonic,我正在寻找一种简写,本质上是:

Literal[range(101)]
Run Code Online (Sandbox Code Playgroud)

不幸的是,上面期望的字面值是range(101)。我也尝试过:

Literal[list(range(101))]
Literal[0:101]
Run Code Online (Sandbox Code Playgroud)

然而,这些失败是因为list并且slice是不可散列的类型。

如何在不输入数字 0 到 100 的情况下执行此操作?

Be3*_*K0T 7

尝试这个:

from typing import Literal

A = Literal[1,2]
B = Literal[(1,2)]
print(A == B) # True

C = Literal[tuple(range(100))]
print(C)
# typing.Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 
# 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 
# 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 
# 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 
# 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 
# 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这是 linters 反对的模式:““Literal”的类型参数必须是 None、文字值(int、bool、str 或 bytes)或枚举值” (6认同)