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

如何为返回特定结构字典的函数填写Dict[]中的类型提示?

函数返回类型注解的正确写法

你的函数返回的是结构明确的字典,有两种合理的类型注解写法:

1. 宽泛的字典类型注解

如果不需要极致严格的类型校验,可以用Dict结合Union来涵盖值的多种类型,需先导入Union:

from typing import Dict, Union

def foo() -> Dict[str, Union[str, Dict[str, Union[str, bool]]]]:
    params = {
        "side": "Buy",
        "symbol": "BTCUSDT",
        "order_type": "Market",
        "time_in_force": "PostOnly",
        "reduce_only": False,
        "close_on_trigger": False,
    }
    return {
        "method": "POST",
        "api": "private/linear/order/create",
        "body": params
    }

这里Dict[str, ...]表示所有键都是字符串类型,值可以是字符串,或是另一个键为字符串、值为字符串/布尔值的字典。

2. 精确的TypedDict类型注解

如果希望类型检查工具(如mypy)能识别每个键对应的具体类型,推荐使用TypedDict(Python 3.8+原生支持,低版本可从typing_extensions导入):

from typing import TypedDict

# 定义body对应的子字典结构
class OrderParams(TypedDict):
    side: str
    symbol: str
    order_type: str
    time_in_force: str
    reduce_only: bool
    close_on_trigger: bool

# 定义返回的顶层字典结构
class OrderRequest(TypedDict):
    method: str
    api: str
    body: OrderParams

def foo() -> OrderRequest:
    params = {
        "side": "Buy",
        "symbol": "BTCUSDT",
        "order_type": "Market",
        "time_in_force": "PostOnly",
        "reduce_only": False,
        "close_on_trigger": False,
    }
    return {
        "method": "POST",
        "api": "private/linear/order/create",
        "body": params
    }

这种方式能明确约束每个键的类型,IDE也能提供更精准的代码提示。

另外注意:你原代码里的Dict[]写法是错误的,Dict必须指定两个类型参数(键类型和值类型),格式为Dict[KeyType, ValueType]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:20:28