This is Python 3.7
I have a dataclass like this:
@dataclass
class Action:
action: str
But action is actually restricted to the values "bla" and "foo". Is there a sensible way to express this?
You could use an 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'
Use typing.Literal
like:
@dataclass
class Action:
action: Literal["bla", "foo"]
The catch is that it's new in Python 3.8. If you want Literal
in earlier Python versions you need to install typing-extensions
module. So, complete solution for Python 3.7 looks like that:
from dataclasses import dataclass
from typing_extensions import Literal
@dataclass
class Action:
action: Literal["bla", "foo"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With