给定以下自定义Literal
:
from typing import Literal, get_args
_ACTIONS = Literal["pasteCharAt", "copyCharAt", "deleteCharAt", "replaceCharAt",
"selectAll", "deleteAll", "copyAll", "pasteAllAt", "click",
"moveLeft", "moveRight"]
我怎样才能产生随机选择它的选项?
为了
print(f'random.choice(_ACTIONS) = {random.choice(_ACTIONS)}')
我只有:
File "C:\python38\lib\random.py", line 288, in choice
i = self._randbelow(len(seq))
TypeError: object of type '_GenericAlias' has no len()
对于以下尝试:
print(f'random.choice(list(_ACTIONS)) = {random.choice(list(_ACTIONS))}')
我也得到了一个错误:
File "C:\python38\lib\typing.py", line 261, in inner
return func(*args, **kwds)
File "C:\python38\lib\typing.py", line 685, in __getitem__
params = tuple(_type_check(p, msg) for p in params)
File "C:\python38\lib\typing.py", line 685, in <genexpr>
params = tuple(_type_check(p, msg) for p in params)
File "C:\python38\lib\typing.py", line 149, in _type_check
raise TypeError(f"{msg} Got {arg!r:.100}.")
TypeError: Parameters to generic types must be types. Got 0.
我使用Python 3.8.6,如果这很重要的话。
1条答案
按热度按时间e4eetjau1#
您可以使用
get_args()
将Literal转换为元组,然后再尝试将其与random.choice()
一起使用。下面是一个例子:这应该给予从定义的
_ACTIONS
Literal中随机选择。