简体   繁体   English

在 Python 中键入提示特定字符​​串的列表

[英]Type hinting a list of specific strings in Python

I have a function as shown below:我有一个如下所示的功能:

from typing import List, Literal, Union


def foo(possible_values: List[Union[Literal['abcd', 'efgh', 'ijkl']]]):
    return {}

Now this is how I want the code to behave:现在这就是我希望代码的行为方式:

whenever the possible_values parameter gets values other than ["abcd", "efgh","ijkl"]每当possible_values参数获取["abcd", "efgh","ijkl"]以外的值时

Eg:例如:

res = foo(possible_values=["abc", "efgh"])

It should throw an error as abc is not defined in the function signature.它应该抛出一个错误,因为abc没有在函数签名中定义。

However,然而,

res = foo(possible_values=["abcd", "efgh"])

should work fine as they are subset of what is defined.应该可以正常工作,因为它们是定义的子集。

Currently, with the above code, it just accepts any arbitrary list of strings.目前,使用上面的代码,它只接受任意字符串列表。

If you want to constrain values to a predefined set, you might want to use Enum .如果要将值限制为预定义的集合,则可能需要使用Enum Like mentioned by others, type hinting won't enforce check and error natively in python, you'll have to either implement it in your function's code, or use a library allowing annotation-based control.就像其他人提到的那样,类型提示不会在 python 中本地强制检查和错误,您必须在函数的代码中实现它,或者使用允许基于注释的控制的库。 Here is an example.这是一个例子。

from typing import List
from enum import Enum

# Let's define your possible values as an enumeration. Note that it also inherits from 
# str, which will allow to use its members in comparisons as if they were strings
class PossibleValues(str, Enum):
    abcd = 'abcd'
    efgh = 'efgh'
    ijkl = 'ijkl'

Now your function.现在你的功能。 Note the type-hinting.注意类型提示。

def foo(possible_values: List[PossibleValues]):
    # We unroll the enum as a set, and check that possible_values is a subset of it
    if not set(PossibleValues).issuperset(possible_values):
        raise ValueError(f'Only {[v.value for v in PossibleValues]} are allowed.')
    # Do whatever you need to do
    return {}

Now when you use it:现在当你使用它时:

foo(['abcd', 'efgh'])
# output: {}
foo(['abc', 'efgh'])
# ValueError: Only ['abcd', 'efgh', 'ijkl'] are allowed.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM