【问题标题】:Can't get past illogical line pep8 error无法通过不合逻辑的行 pep8 错误
【发布时间】:2014-03-20 01:21:37
【问题描述】:

我已经尝试解决这个问题一段时间了,但我无法让它通过 pep8。 这是我的代码:

1.

if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' and 
    sum(regex.count(char) for char in splitter) == 1 and 
    regex.count('(') == 1 and regex.count(')') == 1):

    print('hi')

2.

if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' and 
    sum(regex.count(char) for char in splitter) == 1 and 
    regex.count('(') == 1 and regex.count(')') == 1):

    print('hi')

3.

if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' 
    and regex.count('(') > 1):

    print('hi')

我在 3 个 if 语句中的每一个都收到以下 PEP8 错误:

E125 continuation line does not distinguish itself from next logical line

知道它有什么问题吗?这些行与第一个括号缩进,所以我真的不知道。

【问题讨论】:

  • 到底是什么问题?
  • pep8 给了我以下错误: regex_functions_draft.py:44:9: E125 续行无法与下一个逻辑行区分开来。我尝试用第一个括号正确缩进它,但它似乎不起作用。
  • @FredMitchell 正则表达式只是一个变量,并不相关。 if 语句有效,这就是 pep8 处理我缩进 if 语句的方式。
  • 在 PEP8 模块的 github 页面上还有一个关于这个问题的有趣错误报告:github.com/jcrocholl/pep8/issues/126

标签: python if-statement pep8


【解决方案1】:

1.

if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' and
        sum(regex.count(char) for char in splitter) == 1 and
        regex.count('(') == 1 and regex.count(')') == 1):

    print('hi')

2.

if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' and
        sum(regex.count(char) for char in splitter) == 1 and
        regex.count('(') == 1 and regex.count(')') == 1):

    print('hi')

3.

if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')'
        and regex.count('(') > 1):

    print('hi')

【讨论】:

  • 作为 python 的新手,我上下滚动了 3 次,直到我注意到缩进的差异。 :)
  • There 有一个简短的描述,我在这里引用:这是来自 pep8 的相关声明:续行应该使用 Python 的隐式行在括号、方括号和大括号内连接,或者使用一个悬挂的缩进。使用悬挂缩进时,应考虑以下事项;第一行不应该有任何参数,并且应该使用进一步的缩进来清楚地将自己区分为续行。
【解决方案2】:

我正在使用PyCharm(它非常适合指出 PEP8 错误)进行编辑,它说这个版本还可以:

if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' and
        sum(regex.count(char) for char in splitter) == 1 and
        regex.count('(') == 1 and regex.count(')') == 1):

    print('hi')

【讨论】:

  • 这对我来说似乎很尴尬,因为 sumregex.count 行与它们嵌套的括号不对齐。看起来它们是 len 调用的一部分,而他们在外面。
【解决方案3】:

我并不是说我喜欢这个解决方案,但我认为删除if 之后的空格比将第二行与len 调用的胆量对齐更不妥协,就像这里的其他答案一样建议:

if(len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' and
   sum(regex.count(char) for char in splitter) == 1 and
   regex.count('(') == 1 and regex.count(')') == 1):

    print('hi')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 2022-01-08
    • 2014-07-13
    • 2015-12-18
    • 2021-08-20
    • 1970-01-01
    相关资源
    最近更新 更多