相关疑难解决方法(0)

Python typing: Dynamically Create Literal Alias from List of Valid Values

I have a function which validates its argument to accept only values from a given list of valid options. Typing-wise, I reflect this behavior using a Literal type alias, like so:

from typing import Literal


VALID_ARGUMENTS = ['foo', 'bar']

Argument = Literal['foo', 'bar']


def func(argument: 'Argument') -> None:
    if argument not in VALID_ARGUMENTS:
        raise ValueError(
            f'argument must be one of {VALID_ARGUMENTS}'
        )
    # ...
Run Code Online (Sandbox Code Playgroud)

这违反了 DRY 原则,因为我必须在我的 Literal 类型的定义中重写有效参数列表,即使它已经存储在变量 中VALID_ARGUMENTS给定变量如何Argument动态创建Literal 类型VALID_ARGUMENTS …

python python-typing

8
推荐指数
2
解决办法
1474
查看次数

标签 统计

python ×1

python-typing ×1