潜在返回值列表的 Python 类型注释

问题描述 投票:0回答:1

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
python python-3.x annotations type-hinting python-typing
1个回答
4
投票

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:
    ...
© www.soinside.com 2019 - 2024. All rights reserved.