首页 > 解决方案 > 潜在返回值列表的 Python 类型注释

问题描述

可以用潜在返回值列表注释 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

标签: pythonpython-3.xannotationstype-hintingpython-typing

解决方案


Literal类型似乎是您在此处寻找的类型:

from typing import Literal

def today_is_probably(season) -> Literal[RAINY, SUNNY, CLOUDY, SNOWY]:
    ...

您也可以考虑定义 anenum并将其用作类型。这似乎是这里最合适的方式

import enum

class Weather(enum.Enum):
    RAINY = 'rainy'
    SUNNY = 'sunny'
    CLOUDY = 'cloudy'
    SNOWY = 'snowy'

def today_is_probably(season) -> Weather:
    ...

推荐阅读