如何修复python中不一致的return语句?

Moh*_*taz 5 python string return list

我是 python 新手,我有这个项目我正在做一个带有两个函数的小项目,其中第一个返回第一次在字符串中发现差异的索引。下一个函数执行此操作,但在字符串列表中。现在,由于我是业余爱好者,我使用了过多的 if 和 else 语句,这导致返回语句过多,尤其是在第二个函数中,并且出现错误 [R1710:不一致的返回语句]。我该如何修复它,谁能给我提供更好的代码片段的清晰示例?很抱歉问这么长的问题。

IDENTICAL = -1
def singleline_diff(line1, line2):
    """
    Inputs:
        line1 - first single line string
        line2 - second single line string
    Output:
        Returns the index where the first difference between
        line1 and line2 occurs.

        Returns IDENTICAL if the two lines are the same.
    """
    len1 = len(line1)
    len2 = len(line2)
    minimum_length = min(len1, len2)

    if len1 != len2:
        if minimum_length == 0:
            return 0
        for idx in range(minimum_length):
            if line1[idx] == line2[idx]:
                pass
            else:
                return idx
        return idx + 1

    for idx in range(len1):
        if line1[idx] == line2[idx]:
            pass
        else:
            return idx
    return IDENTICAL

def multiline_diff(lines1, lines2):
    """
    Inputs:
      lines1 - list of single line strings
      lines2 - list of single line strings
    Output:
      Returns a tuple containing the line number (starting from 0) and
      the index in that line where the first difference between lines1
      and lines2 occurs.

      Returns (IDENTICAL, IDENTICAL) if the two lists are the same.
    """
    line_no = singleline_diff(lines1, lines2)

    len_lines1, len_lines2 = len(lines1), len(lines2)

    if len_lines1 == len_lines2:

        if (len_lines1 or len_lines2) == 0:
            if len_lines1 == len_lines2:
                return (IDENTICAL, IDENTICAL)
            else:
                idx = singleline_diff(lines1[line_no], lines2[line_no])
                return (line_no, idx)

        else:
            idx = singleline_diff(lines1[line_no], lines2[line_no])

            if line_no == IDENTICAL:
                return (IDENTICAL, IDENTICAL)
            elif line_no != IDENTICAL:
                return (line_no, idx)

    else:
        return (line_no, 0)
Run Code Online (Sandbox Code Playgroud)

jav*_*web 9

OP 代码中的语义错误在Abhishek Arya 的回答中

TL;DR - 提前返回:

def your_function():
    if not should_do():
        return # NO RETURN VALUE!
    # rest of the function
Run Code Online (Sandbox Code Playgroud)

...是的,这将不再发出inconsistent-return-statements;)

当您搜索时也会弹出此问答inconsistent-return-statements,我想为这些问题提供一个简短的“常见问题”指南。

情况A:返回值无关紧要,你只是想提前退出函数

在某些情况下,有些函数(或“过程”,如果你想了解它的技术)只是做一些事情,但预计不会有任何返回值,
同时,可能会有某种类型在函数开始时检查该函数运行是否有意义,您首先想到的可能是将整个函数代码包装在 if 语句中:

def your_function(article):
    if display_content():
        content = get_content(article)
        # do some extensive logic to generate final content
        # ...
        print(content)
Run Code Online (Sandbox Code Playgroud)

...这过于简单化了,但我们希望您可以想象,如果有更多的检查和更多的代码,这样的编码如何很快就会陷入“意大利面条代码”+它还会窃取您所使用的空间的一个“选项卡”因此迫切需要适应您项目的最大线路长度。

幸运的是,许多其他编程语言一样,有一种方法可以通过在函数运行中的任何return位置处提前结束函数,这意味着在任何“控制流”中- 包括 if/elif/else、for/while循环, ...

现在你可能会快速跳转到return None,False等。虽然它可以工作,但你仍然会收到 pylintinconsistent-return-statements警告 - 要理解为什么让我们看看警告的消息:

函数中的所有 return 语句要么都应该返回表达式 要么都不应该返回。pylint(不一致的返回语句)

从 pylint 的角度来看,如果你在后面添加任何内容,return它将被视为表达式。那么该怎么办?实际上,在 Python 中,你可以返回“nothing”(这并不是 Python 所独有的)

def your_function(article):
    if not display_content():
        return

    content = get_content(article)
    # do some extensive logic to generate final content
    # ...
    print(content)
Run Code Online (Sandbox Code Playgroud)

尽管在Python中返回“nothing”应该是(从技术上来说,据我所知,它是)等价的return None,但通过物理书写“ None”,你正在表达意图,无论它的隐含意义如何。
但不要将其与pylint(assignment-from-none)( Assigning result of a function call, where the function returns None) 混淆 -其中return”和“ return None”都被视为返回None

情况 B:您的函数存在不返回的情况

非常常见的错误,尤其是在较大的代码中,是创建一个导致不返回任何内容的代码部分。这并不完全是OP的情况,因为他们只使用了相同条件的否定,但pylint 不知道这一点,所以这是它的思考过程:

if SOME_CONDITION: # ok, here's just another condition
    return someReturnExpression # and ok, it returns SOMETHING, let's note that
elif OPPOSITE_OF_SOME_CONDITION: # ok, here's just another condition
    return someReturnExpression # and ok, it returns SOMETHING, let's note that
# WAIT ! What?! THERE WAS NO "else:"! Hmmm...
# ...what happens if both conditions fail? NOTHING WOULD BE RETURNED!
# We need to make a warning about that!
# (fact that sometimes they return SOMETHING and sometimes NOTHING)
Run Code Online (Sandbox Code Playgroud)

所以这inconsistent-return-statements可以解决

if SOME_CONDITION: # ok, here's some condition
    return someReturnExpression # and ok, it returns SOMETHING, let's note that
else: # ok, here's else
    return someReturnExpression # and ok, it returns SOMETHING, let's note that
# Ok, so if returns SOMETHING, else returns SOMETHING,
# so SOMETHING is returned every time! that's good!
Run Code Online (Sandbox Code Playgroud)

...这本身是有效的,但它会产生另一个 pylint 问题

“return”之后不必要的“else” pylint(no-else-return)

看到Python实际上鼓励尽早返回,因为它通常会导致更干净的代码。
return在函数运行 ENDS(/exits) 期间,函数和 pylint 看到 - 它看到如果条件为真,函数代码就会在那里结束 - 所以,Abhishek Arya、我和许多其他人建议的只是继续代码if 部分之后:

if SOME_CONDITION:
    return someReturnExpression

# ... some more code ...
# ... some more code ...
return someReturnExpression
Run Code Online (Sandbox Code Playgroud)

案例C:组合

如果您确实需要返回 None 则不要将“just”returnreturn SOMETHING 结合起来,在这种情况下只需明确地返回
return None

def get_article(id):
    article = find_article(id)
    if article.id == 0:
        return None

    return article
Run Code Online (Sandbox Code Playgroud)

这只是一个示例,这并不是您真正检查某些文章的方式;)


Abh*_*rya 6

看这里的代码:

if len_lines1 == len_lines2:
    return (IDENTICAL, IDENTICAL)
else:
    idx = singleline_diff(lines1[line_no], lines2[line_no])
    return (line_no, idx)
Run Code Online (Sandbox Code Playgroud)

你可以把上面的东西写成这样:

if len_lines1 == len_lines2:
    return (IDENTICAL, IDENTICAL)
idx = singleline_diff(lines1[line_no], lines2[line_no])
return (line_no, idx)
Run Code Online (Sandbox Code Playgroud)

你只是不需要 else 块来返回这个表达式,因为如果控件没有进入 if 块,这部分代码将自动被调用。希望能帮助到你。