Python 函数可以用潜在返回值列表进行注释吗?
RAINY = 'rainy'
SUNNY = 'sunny'
CLOUDY = 'cloudy'
SNOWY = 'snowy'
TYPES_OF_WEATHER = [RAINY, SUNNY, CLOUDY, SNOWY]
def today_is_probably(season) -> OneOf[TYPES_OF_WEATHER]:
if season is 'spring':
return RAINY
if season is 'summer':
return SUNNY
if season is 'autumn':
return CLOUDY
if season is 'winter':
return SNOWY
Literal
类型似乎就是您在这里寻找的:
from typing import Literal
def today_is_probably(season) -> Literal['rainy', 'sunny', 'cloudy', 'snowy']:
...
enum
并将其用作类型。看来这里是最合适的方式
import enum
class Weather(enum.Enum):
RAINY = 'rainy'
SUNNY = 'sunny'
CLOUDY = 'cloudy'
SNOWY = 'snowy'
def today_is_probably(season) -> Weather:
...