简体   繁体   中英

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"]

Eg:

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

It should throw an error as abc is not defined in the function signature.

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 . 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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