Typing: Restrict to a list of strings

Viewed 953

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?

3 Answers

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"]

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'

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']):
Related