简体   繁体   中英

Python attribute type hint: list of specific strings?

Is there a type hint that expects a string out of a list of strings?

import typing

@dataclass
class Person:
   name: str = None
   gender: typing.Choice(['male', 'female'])  # <- Something like this?

Person(name='John', gender='male')   # okay
Person(name='John', gender='female') # okay
Person(name='John', gender='apple')  # error

Thanks!

Multiple options:

from typing import Literal
gender = Literal['male', 'female', 'other']
from enum import Enum
class Gender(Enum):
   FEMALE = "female"
   MALE = "male"
   OTHER = "other"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM