10

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?

Christian Sauer
  • 10,351
  • 10
  • 53
  • 85

3 Answers3

9

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"]
Tupteq
  • 2,986
  • 1
  • 21
  • 30
7

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'
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

Just adding an example for limiting, accepted strings in a function

from typing import Literal

def get_time_measurement(message, unit: Literal['nanosec', 'microsec', 'millisec']):
Arindam Roychowdhury
  • 5,927
  • 5
  • 55
  • 63