【问题标题】:Python type hints: how to do a literal rangePython 类型提示:如何进行文字范围
【发布时间】:2021-06-21 09:49:13
【问题描述】:

我使用 pydantic 的类型提示为我的 Python API 设置返回模式。

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

from typing import Literal
MyType = Literal[0, 1, 2, ... , 99, 100]

这不是特别pythonic,我正在寻找一种速记,本质上是:

Literal[range(101)]

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

Literal[list(range(101))]
Literal[0:101]

但是这些都失败了,因为 listslice 是不可散列的类型。

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

【问题讨论】:

标签: python literals type-hinting pydantic


【解决方案1】:

Literal 将参数保存为Literal.__dict__['__args__'],这样你就可以这样做

from typing import Literal


mytype = Literal[1]
mytype.__dict__['__args__'] = list(range(1, 101))

【讨论】:

    【解决方案2】:

    特别是对于 Pydantic,您可以使用验证器来模拟 Literal 范围:

    from pydantic import BaseModel, validator
    
    class MySchema(BaseModel):
        val: int
    
        @validator('val')
        def validate_range(cls, v):
            if v < 0 or v > 100:
                raise ValueError('Val must be in the range 0-100')
            return v
    

    【讨论】:

      【解决方案3】:

      试试这个:

      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]
      

      【讨论】:

        猜你喜欢
        • 2021-03-29
        • 1970-01-01
        • 2018-03-23
        • 2012-10-30
        • 2012-04-17
        • 1970-01-01
        • 2016-07-04
        • 1970-01-01
        • 2011-12-04
        相关资源
        最近更新 更多