关于良好的编码实践,"Useless return at end of function and method" 是什么意思?

Regarding good coding practices, what is meant by "Useless return at end of function and method"?

我正在使用 Spyder 创建网络抓取工具,目前进展顺利。作为菜鸟,Spyder 的代码分析功能对我提高代码水平很有帮助。然而,虽然我通常理解它 instructions/recommendations,但我最近 运行 遇到了一些问题。我先 post 一些示例代码:

def payments(): #### This is line 59 on the editor. Preceding it is another function with a a format similar to this one.
    """Obtains data on the weekly payments in the country"""
    html = get(source["Payments"]).text
    html = bs(html,"lxml")
    location = "/home/oduduwa/Desktop/Python Projects/Financial Analyser/CBN Data/Payments.csv"
    def file_check():
        headings = [i.text for i in html.find_all(width="284")][:10]
        headings.insert(0, "Date")
        if isfile(location) is False:
            with open(location,"w") as file_obj:
                writer(file_obj).writerow(headings)
                return
    file_check()
    file = open(location,"r").read()
    dates = [i.text.strip()[8:] for i in html.find_all("th",colspan="2")]
    values = [i.text.strip()[4:] for i in html.find_all(width="149") if i.text.strip()[4:]!=""]
    values = array(values).reshape(int(len(values)/10),10)
    values = insert(values,0,array(dates).transpose(),axis=1)[::-1]
    for i in range(len(values)):
        if values[i][0] not in file:
            with open(location,"a+",newline=("\n")) as file_obj:
                writer(file_obj).writerow(values[i])
    return

代码 运行 完成并完成了它应该做的一切。然而,我真正不明白的是 Spyder 的声明,即代码块中有一个无用的 return 调用。这是它具体说的:

但据我所知,此编码块中的每个函数调用都是必需的。我错过了什么?感谢您的宝贵时间!

你误会了。警告不是在谈论您正在调用的任何功能。它指的是您使用 return 关键字。

这个函数:

def print_hello():
    print("Hello")
    return

相当于这个函数:

def print_hello():
    print("Hello")
    return None

相当于这个函数:

def print_hello():
    print("Hello")

警告是说,您的 return 语句没有用,不需要。

默认情况下,

Python 隐式运行 return None。以下函数定义是等价的。

def foo():
    pass

def foo():
    return

def foo():
    return None

在我看来,

  1. 根本没有 return 语句 - 这表明您在调用函数时不应该为 return 值分配名称,或者
  2. 明确地 return None,以指示可能 return 有意义的值的函数“无结果”,或
  3. 仅使用 return 使 return 没有有意义的值的函数停止执行。

情况 1 的示例:

def switch_first_last_in_place(lst):
    'switch the first and last elements of a list in-place'
    lst[0], lst[-1] = lst[-1], lst[0]

这个函数隐式 returns None 而你 应该发布

result = switch_first_last_in_place([1, 2, 3])

情况 2 的示例:

def get_user_info_from_database(username):
    'fetches user info, returns None if user does not exist'
    if user_exist(username):
        return query_db(username)
    else:
        return None

此函数显式 returns None 以指示未找到用户。作业如

result = get_user_info_from_database('Bob')

符合预期。部分

else:
    return None

不必要的 但我喜欢在 None 是有意义的 return 值的情况下明确。

情况 3 的示例:

def assert_exists(thing, *containers):
    'raise AssertionError if thing cannot be found in any container'
     for container in containers:
         if thing in container:
             return
     raise AssertionError

这里,return只是用来跳出函数的。


我不喜欢你示例中函数末尾的 return。它不用于结束执行,这些函数不能 return 其他值。我会删除它。