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

Python中不调用方法如何校验其是否包含return语句

检测Python方法是否包含显式return语句的实现

可以通过Python内置的ast(抽象语法树)模块和inspect模块做静态代码分析,无需执行函数即可判断是否包含显式return语句,具体实现如下:

基础版本实现

import ast
import inspect

def has_explicit_return(func):
    # 获取目标函数的源码
    source_code = inspect.getsource(func)
    # 解析源码为抽象语法树
    ast_tree = ast.parse(source_code)
    # 遍历所有语法节点查找Return节点
    for node in ast.walk(ast_tree):
        if isinstance(node, ast.Return):
            return True
    return False

效果测试

使用你给出的示例类测试:

class class1():
    def __init__(self):
        pass
    def method1(self):
        return 0
    def method2(self):
        raise NotImplementedError

object1 = class1()

# 测试输出
print(has_explicit_return(object1.method1))  # 输出 True
print(has_explicit_return(object1.method2))  # 输出 False

# 断言测试
assert has_explicit_return(object1.method1)  # 无报错
assert has_explicit_return(object1.method2)  # 抛出 AssertionError

注意事项&优化方案

  • 该方案仅适用于可获取源码的Python实现函数,C语言实现的内置函数(如len)无法通过inspect.getsource获取源码,会抛出异常。
  • 基础版本会把函数内部嵌套定义的函数/类中的return误判为外层函数的return,如果需要规避这个问题,可以使用如下严格版本的实现:
def has_explicit_return_strict(func):
    source_code = inspect.getsource(func)
    ast_tree = ast.parse(source_code)
    func_def_node = ast_tree.body[0]
    # 仅遍历当前函数自身的代码块,跳过嵌套的函数、类定义
    for node in ast.walk(func_def_node.body):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
            continue
        if isinstance(node, ast.Return):
            return True
    return False
  • 如果你需要的不是「是否包含return语句」,而是「所有执行路径都有显式返回值」,可以基于ast做控制流分析,或者借助mypy等静态类型检查工具实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:57:04