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

如何为返回函数列表的Python函数指定正确的返回类型?

解决函数列表的返回类型标注问题

你遇到的NameError是因为Python里没有名为function的内置类型,typing库也不存在Function这个对象。要正确标注返回函数列表的类型,需要用**Callable**类型,具体步骤如下:

1. 导入正确的类型

  • 若使用Python 3.8及更早版本,需从typing模块导入Callable和List:
    from typing import List, Callable
    
  • 若使用Python 3.9+,可直接使用标准库的collections.abc.Callable,同时用原生list替代typing.List:
    from collections.abc import Callable
    

2. 修改返回类型标注

你的get_next_actions函数返回的是**接受AutomatorDevice参数、返回None**的函数列表,所以要做精确的类型标注:

Python 3.8及以下版本

@typechecked
def get_next_actions(
    self,
    required_objects: Dict[str, str],
    optional_objects: Dict[str, str],
) -> List[Callable[[AutomatorDevice], None]]:
    print(
        "TODO: determine how to specify how to compute the next action"
        + f" for this screen. {required_objects},{optional_objects}"
    )
    return [actions_1, actions_2]

Python 3.9+版本

@typechecked
def get_next_actions(
    self,
    required_objects: dict[str, str],
    optional_objects: dict[str, str],
) -> list[Callable[[AutomatorDevice], None]]:
    print(
        "TODO: determine how to specify how to compute the next action"
        + f" for this screen. {required_objects},{optional_objects}"
    )
    return [actions_1, actions_2]

说明

Callable[[参数类型], 返回值类型]是Python类型标注中描述函数类型的标准写法。因为你的actions_1和actions_2都符合「接收AutomatorDevice参数、返回None」的特征,用这个标注能让类型检查器准确验证返回值的合法性,避免类型错误。

内容的提问来源于stack exchange,提问作者a.t.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:05:41