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

如何在类初始化时检查传入函数的返回类型(不执行函数)

不执行函数验证返回类型的实现方案

思路1:利用函数的类型注解(Python 3.5+)

如果传入的函数定义了返回类型注解,我们可以直接通过代码提取注解信息完成验证,完全不需要执行函数。

代码示例:

import types
import numpy as np
from typing import get_type_hints

class NewClass:
    def __init__(self, function):
        # 先检查参数是否为函数类型
        if not isinstance(function, types.FunctionType):
            raise TypeError("传入的参数必须是函数")
        
        # 提取并验证返回类型注解
        try:
            type_info = get_type_hints(function)
            return_type = type_info.get('return')
            if return_type is np.ndarray:
                self.function = function
            else:
                raise TypeError(f"函数返回类型必须是numpy.ndarray,当前注解为{return_type}")
        except NameError:
            raise TypeError("无法解析函数的返回类型注解")

测试用带注解函数:

def new_fun() -> np.ndarray:
    return np.zeros((2,2,2,2))

obj = NewClass(new_fun)  # 可正常初始化

思路2:处理无类型注解的函数(折中方案)

如果函数没有添加类型注解,不执行函数的前提下无法100%确定其返回类型——毕竟Python是动态类型语言,返回类型只有运行时才能确定。这种情况可以采用以下折中办法:

  • 要求所有传入的函数必须显式添加返回类型注解(适合内部项目或团队协作场景)
  • 让用户手动指定预期返回类型,后续首次调用函数时再做验证(仅付出一次运行开销):
import types
import numpy as np

class NewClass:
    def __init__(self, function, expected_return=np.ndarray):
        if not isinstance(function, types.FunctionType):
            raise TypeError("传入的参数必须是函数")
        
        self.function = function
        self._expected_type = expected_return
    
    def run(self, *args, **kwargs):
        result = self.function(*args, **kwargs)
        if not isinstance(result, self._expected_type):
            raise TypeError(f"返回类型不符合预期,应为{self._expected_type},实际为{type(result)}")
        return result

关键注意事项

  • 类型注解是Python的可选特性,依赖注解验证的话,需要确保所有传入的函数都正确添加了注解
  • 动态类型语言的特性决定了,不执行函数就无法做到绝对准确的返回类型校验,上述方法均是基于约定或注解的规则校验,而非实际运行时的类型检查

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:05:44