我喜欢 @st0le 检查源代码的想法,但您可以更进一步,将源代码解析为源代码树,这消除了误报的可能性。
import ast
import inspect
def contains_explicit_return(f):
return any(isinstance(node, ast.Return) for node in ast.walk(ast.parse(inspect.getsource(f))))
def f1():
return 1
def f2():
return None
def f3():
print("return")
for f in (f1, f2, f3):
print(f, contains_explicit_return(f))
Result:
<function f1 at 0x01D151E0> True
<function f2 at 0x01D15AE0> True
<function f3 at 0x0386E108> False
当然,这只适用于以下功能have源代码是用 Python 编写的,但并非所有函数都是如此。例如,contains_explicit_return(math.sqrt)
会给你一个类型错误。
此外,这不会告诉您任何有关函数的任何特定执行是否命中 return 语句的信息。考虑以下功能:
def f():
if random.choice((True, False)):
return 1
def g():
if False:
return 1
contains_explicit_return
会给True
在这两方面,尽管f
一半的执行没有遇到返回,并且g
没有遇到返回ever.
最后,它不会区分函数是否有 return 语句或内部定义的函数是否有 return 语句:
def f():
def g():
return 5
在这种情况下,contains_explicit_return(f)
将返回True
, 虽然f
永远不会返回任何东西,因为该函数g
inside 包含显式返回。