PyCharm中Literal结合Enum的重载类型提示失效问题
枚举类型配合@overload与Literal时未触发预期类型警告的问题
需求
我想为重载函数添加类型提示,使用typing模块的@overload装饰器,根据color参数的不同值定义多种调用签名。
问题代码
from typing import Literal, overload from enum import Enum class Color(Enum): RED = 0 BLUE = 1 GREEN = 2 @overload def func( *, title: str, color: Literal[Color.RED, Color.BLUE], description: str, ) -> None: ... @overload def func( *, title: str, color: Literal[Color.GREEN], ) -> None: ... def func( *, title: str = None, color: Color = None, description: str = None, ) -> None: print(title, color, description) func(title="hello", color=Color.GREEN, description="hello")
现象对比
- 当
color设为Color.GREEN时传入description参数,未收到预期警告:PyCharm中该调用未显示任何类型错误提示 - 改用字符串字面量实现相同逻辑时功能正常:将
Literal替换为Literal["red", "blue"]和Literal["green"],color类型改为str,此时PyCharm会触发预期警告,提示传入了未预期的description参数 - 不传入
description参数时无错误,符合预期:PyCharm中无类型提示错误
环境信息
Python 3.8,IDE:PyCharm
内容的提问来源于stack exchange,提问作者codeofandrin
相关产品推荐
相关产品推荐

