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

如何为可返回空集合或字典的函数添加类型提示?

集合类型提示问题
  • 函数返回空集合或字符串集合时,直接用set[str]作为返回值类型提示即可(Python 3.9及以上支持原生集合类型标注,3.9以下版本可改用typing.Set[str])。
  • set[str]完全允许空集合:空集合没有元素,不存在元素类型不符合str的情况,因此空集合属于set[str]的合法实例。

示例代码:

def get_string_collection() -> set[str]:
    if check_something():
        return set()  # 空集合,符合类型提示
    return {"string1", "string2"}
字典类型提示问题
  • 对于返回空字典或键为字符串、值为字符串/布尔值/字符串列表的函数,类型提示应为dict[str, str | bool | list[str]](Python 3.10及以上支持|表示联合类型;3.10以下版本需用typing.Union,写成Dict[str, Union[str, bool, List[str]]])。
  • dict[str, str | bool | list[str]]允许空字典:空字典没有键值对,不会出现键类型非字符串、值类型不符合指定范围的情况,因此是合法的。

示例代码(Python 3.10+):

def get_mixed_dict() -> dict[str, str | bool | list[str]]:
    if check_something():
        return {}  # 空字典,符合类型提示
    return {
        "username": "sjk05",
        "is_verified": True,
        "tags": ["python", "typing"]
    }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 02:13:12