You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 04:37:10