python - 潜在返回值列表的 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
解决方案
该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:
...
推荐阅读
- reactjs - 容器组件中的访问状态
- python-3.x - 如何在数据框中为每个唯一 ID 执行操作?
- javascript - Express Router Regex - 如何匹配包含连字符的字符串文字?
- php - Imap-open 没有连接到 Gmail - SELinux 问题
- angular - 带有多选表单更改事件的angular6-json-schema-form问题
- php - curl没有下载所有pdf文件PHP
- string - 读取和绘制 2 个列中的经度和纬度数据
- tkinter - 从另一个窗口更新一个窗口的文本小部件
- c++ - 使用 bjam 构建提升时没有任何反应
- php - 如何更新图像?