Skip to content Skip to sidebar Skip to footer

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: f

Solution 1:

Go the other way around, and build VALID_ARGUMENTS from Argument:

Argument = typing.Literal['foo', 'bar']
VALID_ARGUMENTS: typing.Tuple[Argument, ...] = typing.get_args(Argument)

It's possible at runtime to build Argument from VALID_ARGUMENTS, but doing so is incompatible with static analysis, which is the primary use case of type annotations. Building VALID_ARGUMENTS from Argument is the way to go.

I've used a tuple for VALID_ARGUMENTS here, but if for some reason you really prefer a list, you can get one:

VALID_ARGUMENTS: typing.List[Argument] = list(typing.get_args(Argument))

Solution 2:

If anyone's still looking for a workaround for this:

typing.Literal[tuple(VALID_ARGUMENTS)]

Solution 3:

Here is the workaround for this. But don't know if it is a good solution.

VALID_ARGUMENTS = ['foo', 'bar']

Argument = Literal['1']

Argument.__args__ = tuple(VALID_ARGUMENTS)

print(Argument)
# typing.Literal['foo', 'bar']

Post a Comment for "Typing: Dynamically Create Literal Alias From List Of Valid Values"