Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typing: Restrict to a list of strings

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?

like image 931
Christian Sauer Avatar asked Mar 09 '20 11:03

Christian Sauer


2 Answers

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'
like image 154
user2390182 Avatar answered Sep 24 '22 23:09

user2390182


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"]
like image 34
Tupteq Avatar answered Sep 23 '22 23:09

Tupteq