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

如何为run函数编写针对动态bool的第三种重载且不冲突?

问题:为run函数的动态bool参数编写不冲突的重载

我正在编写自定义run函数,想为text参数的动态bool值新增第三个重载,要求这个重载不会和已有的Literal[False]、Literal[True]重载产生冲突。

现有代码如下:

from __future__ import annotations
from typing import TypeVar, overload, Optional, Literal, Union

T = TypeVar('T', str, bytes)

# 如果text为False或默认值,input必须是bytes,返回bytes
@overload
def run(text: Literal[False] = False, input: Optional[bytes] = ...) -> bytes: ...
# 如果text为True,input必须是str,返回str
@overload
def run(text: Literal[True], input: Optional[str] = ...) -> str: ...
# 当text是未知的动态bool值时,input和返回值类型需一致
#@overload
#def run(text: bool, input: Optional[Union[str, bytes]] = ...) -> Union[str, bytes]: ...
#def run(text: bool, input: Optional[T] = ...) -> T: ...


def run(text: bool = False, input: Optional[Union[str, bytes]] = None) -> Union[str, bytes]: return ""

# 预期的调用检查结果
run(input="")  # 应该报错
run(input=b"")  # 合法
run(False, "")  # 应该报错
run(False, b"")  # 合法
run(True, "")  # 合法
run(True, b"")  # 应该报错
def test() -> bool: ...
run(test(), "")  # 合法
run(test(), b"")  # 合法

目前取消第三个重载的注释后,所有调用都会被判定为合法,但我希望这个重载只匹配**text是动态bool值(非字面量True/False)**的情况,不要成为“万能匹配”覆盖前两个重载的规则,请问这是否可行?

内容的提问来源于stack exchange,提问作者KamilCuk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 17:57:02