Python 检查函数是否有返回语句 [英] Python Check if function has return statement
问题描述
例如
def f1():
return 1
def f2():
return None
def f3():
print("Hello")
函数 f1()
和 f2()
会返回一些东西,但 f3()
不会.
Functions f1()
and f2()
returns something but f3()
not.
a = f2()
b = f3()
这里 a
等于 b
所以我不能只比较函数的结果来检查一个函数是否有 return
.
And here a
equals b
so I can't just compare the result of functions to check if one has return
or not.
推荐答案
我喜欢 st0le 的检查源的想法,但你可以更进一步,将源解析为源树,这样可以消除误报的可能性.
I like st0le's idea of inspecting the source, but you can take it a step further and parse the source into a source tree, which eliminates the possibility of false positives.
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))
结果:
<function f1 at 0x01D151E0> True
<function f2 at 0x01D15AE0> True
<function f3 at 0x0386E108> False
当然,这仅适用于具有用 Python 编写的源代码的函数,并非所有函数都适用.例如,contains_explicit_return(math.sqrt)
会给你一个 TypeError.
Of course, this only works for functions that have source code written in Python, and not all functions do. For instance, contains_explicit_return(math.sqrt)
will give you a TypeError.
此外,这不会告诉您有关函数的任何特定执行是否命中 return 语句的任何信息.考虑函数:
Furthermore, this won't tell you anything about whether any particular execution of a function hit a return statement or not. Consider the functions:
def f():
if random.choice((True, False)):
return 1
def g():
if False:
return 1
contains_explicit_return
将在这两个上给出 True
,尽管 f
在其执行的一半中没有遇到返回,并且 g
永远没有遇到返回.
contains_explicit_return
will give True
on both of these, despite f
not encountering a return in half of its executions, and g
not encountering a return ever.
这篇关于Python 检查函数是否有返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!