【问题标题】:Python Check if function has return statementPython 检查函数是否有返回语句
【发布时间】:2018-06-22 07:15:39
【问题描述】:

例如

def f1():
    return 1

def f2():
    return None

def f3():
    print("Hello")

函数f1()f2() 返回一些东西,但f3() 不返回。

a = f2()
b = f3()

这里a 等于b,所以我不能只比较函数的结果来检查一个是否有return

【问题讨论】:

  • f3() 返回None,因为如果您未在 Python 中指定返回,则默认返回为无。我假设您在问是否可以检查用户是否实际指定了退货?
  • 你能举一个例子来说明区分“显式返回无”和“隐式返回无”的地方吗?

标签: python return


【解决方案1】:

我喜欢 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))

结果:

<function f1 at 0x01D151E0> True
<function f2 at 0x01D15AE0> True
<function f3 at 0x0386E108> False

当然,这仅适用于具有用 Python 编写的源代码的函数,并非所有函数都适用。例如,contains_explicit_return(math.sqrt) 会给你一个 TypeError。

此外,这不会告诉您任何特定的函数执行是否命中了 return 语句。考虑函数:

def f():
    if random.choice((True, False)):
        return 1

def g():
    if False:
        return 1

contains_explicit_return 将在这两个上给出True,尽管f 在其执行的一半中没有遇到返回,并且g 没有遇到返回永远

【讨论】:

    【解决方案2】:

    根据定义,函数总是返回一些东西。即使不指定,python 函数末尾也有隐含的return None

    您可以使用检查模块检查“返回”。

    编辑:我刚刚意识到。这是非常错误的,因为如果函数中有一个包含“return”的字符串文字,它将返回 True。我想一个健壮的正则表达式会在这里有所帮助。

    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))
    

    【讨论】:

      猜你喜欢
      • 2011-10-02
      • 2015-01-02
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 2011-10-26
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多