首页 > 解决方案 > 关于良好的编码实践,“函数和方法结束时无用的返回”是什么意思?

问题描述

我正在使用 Spyder 创建一个网络爬虫,到目前为止一切进展顺利。作为一个菜鸟,我发现 Spyder 的代码分析功能对提高我的代码标准很有用。然而,虽然我通常理解它的说明/建议,但我最近遇到了一些问题。我将首先发布一些示例代码:

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 的声明,即代码块中有一个无用的返回调用。这是它具体说的: 在此处输入图像描述

但据我所知,这个编码块中的每个函数调用都是必需的。我可能错过了什么?谢谢你的时间!

标签: pythonfunctionspyderconventions

解决方案


Python 函数None默认隐式返回。以下函数定义是等效的。

def foo():
    pass

def foo():
    return

def foo():
    return None

在我看来,这是一个很好的做法

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

情况 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]

这个函数隐式返回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

此函数显式返回None以指示未找到用户。像这样的作业

result = get_user_info_from_database('Bob')

预计。那个部分

else:
    return None

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

情况 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您示例中函数末尾的裸露。它不用于结束执行,并且这些函数不能返回其他值。我会删除它。


推荐阅读