键入:限制为字符串列表
Typing: Restrict to a list of strings
这是Python3.7
我有一个这样的数据类:
@dataclass
class Action:
action: str
但操作实际上仅限于值 "bla" 和 "foo"。有什么合理的表达方式吗?
像这样使用typing.Literal
:
@dataclass
class Action:
action: Literal["bla", "foo"]
问题是它是 Python 3.8 中的新功能。如果你想在早期的 Python 版本中使用 Literal
,你需要安装 typing-extensions
模块。因此,Python 3.7 的完整解决方案如下所示:
from dataclasses import dataclass
from typing_extensions import Literal
@dataclass
class Action:
action: Literal["bla", "foo"]
您可以使用 Enum
:
from dataclasses import dataclass
from enum import Enum
class ActionType(Enum):
BLA = 'bla'
FOO = 'foo'
@dataclass
class Action:
action: ActionType
>>> a = Action(action=ActionType.FOO)
>>> a.action.name
'FOO'
>>> a.action.value
'foo'
只是在函数中添加一个限制、接受字符串的例子
from typing import Literal
def get_time_measurement(message, unit: Literal['nanosec', 'microsec', 'millisec']):
这是Python3.7
我有一个这样的数据类:
@dataclass
class Action:
action: str
但操作实际上仅限于值 "bla" 和 "foo"。有什么合理的表达方式吗?
像这样使用typing.Literal
:
@dataclass
class Action:
action: Literal["bla", "foo"]
问题是它是 Python 3.8 中的新功能。如果你想在早期的 Python 版本中使用 Literal
,你需要安装 typing-extensions
模块。因此,Python 3.7 的完整解决方案如下所示:
from dataclasses import dataclass
from typing_extensions import Literal
@dataclass
class Action:
action: Literal["bla", "foo"]
您可以使用 Enum
:
from dataclasses import dataclass
from enum import Enum
class ActionType(Enum):
BLA = 'bla'
FOO = 'foo'
@dataclass
class Action:
action: ActionType
>>> a = Action(action=ActionType.FOO)
>>> a.action.name
'FOO'
>>> a.action.value
'foo'
只是在函数中添加一个限制、接受字符串的例子
from typing import Literal
def get_time_measurement(message, unit: Literal['nanosec', 'microsec', 'millisec']):