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

如何在Python中遍历文件内所有函数并检测返回类型

可行的实现方案

当然可以实现需求,原代码直接遍历模块对象foo不可行——因为模块本身不是可迭代对象,需要先筛选出模块内的目标函数,再逐一测试。以下是具体实现方式:

基础实现方式

通过dir()获取模块的所有属性名,结合inspect模块判断属性是否为函数,再进行验证:

# test_foo.py
import foo
import inspect

def test_foo():
    # 遍历模块的所有属性名称
    for attr_name in dir(foo):
        # 跳过私有属性(可选,避免测试模块内置的私有对象)
        if attr_name.startswith('_'):
            continue
        # 获取属性对应的对象
        attr_obj = getattr(foo, attr_name)
        # 仅处理函数类型的对象
        if inspect.isfunction(attr_obj):
            # 调用函数并验证返回值类型
            assert isinstance(attr_obj(1), int), f"函数{attr_name}返回值非int类型"

精准筛选目标函数

如果只想测试bar_前缀的函数,可以在筛选时增加命名规则判断,避免误测模块内其他函数:

# test_foo.py
import foo
import inspect

def test_foo():
    for attr_name in dir(foo):
        # 仅处理以bar_开头的函数
        if attr_name.startswith('bar_'):
            attr_obj = getattr(foo, attr_name)
            if inspect.isfunction(attr_obj):
                assert isinstance(attr_obj(1), int), f"函数{attr_name}返回值非int类型"

优化测试体验(基于pytest框架)

如果使用pytest测试框架,可以用参数化测试让每个函数的测试结果独立展示,更便于定位问题:

# test_foo.py
import pytest
import foo
import inspect

# 预先筛选出所有bar_前缀的函数作为测试用例
test_functions = [
    getattr(foo, name) 
    for name in dir(foo) 
    if name.startswith('bar_') and inspect.isfunction(getattr(foo, name))
]

# 参数化测试,每个函数单独生成测试用例
@pytest.mark.parametrize("func", test_functions, ids=[f.__name__ for f in test_functions])
def test_bar_functions(func):
    assert isinstance(func(1), int)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:48:51