擅长:python、mysql、java
<p>根据定义,函数总是返回某些值。即使不指定它,在python函数的末尾也有一个隐式的<code>return None</code>。在</p>
<p>您可以使用inspect模块检查“返回”。在</p>
<p><strong>编辑</strong>:我刚刚意识到。这是非常错误的,因为如果函数中有一个字符串文本包含“return”,那么它将返回True。我想一个健壮的正则表达式会有帮助。在</p>
<pre><code>from inspect import getsourcelines
def f(n):
return 2 * n
def g(n):
print(n)
def does_function_have_return(func):
lines, _ = getsourcelines(func)
return any("return" in line for line in lines) # might give false positives, use regex for better checks
print(does_function_have_return(f))
print(does_function_have_return(g))
</code></pre>