E701 multiple statements on one line colon python как исправить

Multiple statements on one line (colon)

Multiple statements should be on their own separate lines. This improves readability.

Anti-pattern

if x > 5: y = 10

Best practice

if x > 5:
    y = 10

I’m using flake8 in Visual Studio Code, writing some code using Python 3.6 variable annotations. It worked without any problems so far, but I encountered a strange warning.

This works fine:

style: str = """
width: 100%;
...
"""
# Doing sth with `style`

This too:

img_style: str = """
width: 100%;
...
"""
# Doing sth with `img_style`

This however does not, it yields below warning:

iframe_style: str = """
width: 100%;
...
"""
# Doing sth with `iframe_style`

flake8 warning

Well, technically it does work fine; the code runs. But somehow flake8 is not happy with this.
The multiline string and the code following is always the same.

When I omit the «f» (i_rame_style), I don’t get a warning, too! So I guess for some reason flake8 thinks of a if foo: bar() here!?

What am I missing here? Is this a bug in flake8?

asked Apr 11, 2018 at 11:50

linusg's user avatar

linusglinusg

6,2334 gold badges28 silver badges77 bronze badges

6

Edit: The problem is in pycodestyle (pep8), which is called by flake8. The rest still stands.

Second edit: I’ve made some more research and the issue is fixed here. The fix hasn’t been released yet, though.

Definitely looks like a flake8 bug to me:

flakebug.py:

innocuous: str = ""
ifstarting_string: str = ""
forfalse_positivetoo: str = ""
whilethis_lookslikeabug: str = ""
elsehaha: str = ""

In the shell:

$ # python3.6 -m pycodestyle flakebug.py gives the same results
$ python3.6 -m flake8 flakebug.py 
flakebug.py:2:18: E701 multiple statements on one line (colon)
flakebug.py:3:21: E701 multiple statements on one line (colon)
flakebug.py:4:24: E701 multiple statements on one line (colon)
flakebug.py:5:9: E701 multiple statements on one line (colon)

Looks like every line starting with a control flow statement triggers it.
I’d wager it uses a regex like (if|else|while|for).*:.

I’ll try to get to the bottom of this and update this answer if I can, meanwhile you could add some # noqa annotations and you’ll be set :)

answered Apr 11, 2018 at 12:07

etene's user avatar

eteneetene

7004 silver badges12 bronze badges

4

Comments

@futursolo

eddie-dunn

pushed a commit
to eddie-dunn/pycodestyle
that referenced
this issue

Jun 9, 2017

If a Python 3 class variable begins with an indent keyword, i.e.,

class Class:
    with_foo: int

pycodestyle will erroneously output the error 'E701 multiple statements
on one line'. This patch tightens the check so that even variables
beginning with indent keywords are allowed.

Resolves PyCQA#635

LefterisJP

added a commit
to LefterisJP/raiden
that referenced
this issue

Aug 9, 2018

@LefterisJP

LefterisJP

added a commit
to LefterisJP/raiden
that referenced
this issue

Aug 9, 2018

@LefterisJP

LefterisJP

added a commit
to raiden-network/raiden
that referenced
this issue

Aug 10, 2018

@LefterisJP

calin-iorgulescu

added a commit
to calin-iorgulescu/hangups
that referenced
this issue

Nov 22, 2018

@calin-iorgulescu

calin-iorgulescu

added a commit
to calin-iorgulescu/hangups
that referenced
this issue

Nov 22, 2018

@calin-iorgulescu

calin-iorgulescu

added a commit
to calin-iorgulescu/hangups
that referenced
this issue

Nov 22, 2018

@calin-iorgulescu

LefterisJP

added a commit
to LefterisJP/raiden
that referenced
this issue

Feb 7, 2019

@LefterisJP

With a new version of flake8 we can now stop ignoring E701 that was
introduced to this bug: PyCQA/pycodestyle#635

LefterisJP

added a commit
to raiden-network/raiden
that referenced
this issue

Feb 7, 2019

@LefterisJP

With a new version of flake8 we can now stop ignoring E701 that was
introduced to this bug: PyCQA/pycodestyle#635

hackaugusto

pushed a commit
to hackaugusto/raiden
that referenced
this issue

Feb 21, 2019

@LefterisJP

@hackaugusto

With a new version of flake8 we can now stop ignoring E701 that was
introduced to this bug: PyCQA/pycodestyle#635

Python’s PEP8 code specification, so record the common PEP8 code specification problems and solutions, learn it, and continue to update when you encounter it, develop good habits, and write standardized code!

PEP 8: no newline at end of file

Solution: You need to start a new line at the end of the code and move the cursor to the last carriage return

  • PEP 8: indentation is not a multiple of four
    Solution: Indent is not a multiple of 4, check indent

  • PEP 8: over-indented
    Solution: Excessive indentation, check indentation

  • PEP 8: missing whitespace after’,’
    Solution: There are fewer spaces after the comma, just add spaces, similar to the semicolon or colon after the missing spaces

  • PEP 8: multiple imports on one line
    Solution: Do not refer to multiple libraries in one sentence, for example:import socket, urllib.errorIt is best written as:import socket import urllib.error

  • PEP 8: blank line at end of line
    Solution: There are more spaces at the end of the code, just delete the spaces

  • PEP 8: at least two spaces before inline comment
    Solution: There must be at least two spaces between the code and the comment

  • PEP 8: block comment should start with ‘#’
    Solution: The comment should start with # plus a space

  • PEP 8: inline comment should start with ‘#’
    Solution: The comment should start with # plus a space

  • PEP 8: module level import not at top of file
    Solution: import is not at the top of the file, there may be other code before

  • PEP 8: expected 2 blank lines,found 0
    Solution: Two blank lines are needed, add two blank lines

  • PEP 8: function name should be lowercase
    Solution: Change the function name to lower case

  • PEP 8: missing whitespace around operator
    Solution: Operators (’=’, ‘>’, ‘<’, etc.) lack spaces before and after, just add

  • PEP 8: unexpected spaces around keyword / parameter equals
    Solution: Unexpected spaces appear around the keyword / parameter equal sign, just remove the spaces

  • PEP 8: multiple statements on one line (colon)
    Solution: The multi-line statement is written to one line, for example:if x == 2: print('OK')Write in two lines

  • PEP 8: line too long (82 > 79 characters)
    Solution: The maximum length limit of each line is exceeded 79

  • PEP 8: Simplify chained comparison
    can simplify chain comparisons (for example:if a >= 0 and a <= 9: Can be abbreviated as:if 0 <= a <= 9:


  • If you want to selectively ignore the warning message of the PEP8 code style, you can use the following methods: (Cultivate good habits and write standardized code! It is not recommended to ignore!)

    ①Move the mouse to the place where the warning message appears, pressalt+Enter, Choose to ignore (Ignore) this error:

    ②Select one by oneFile — Settings — Editor — Inspections, Found under PythonPEP8 coding style violation Options, in the lower right cornerIgnore errors Click the plus sign to add the warning message ID that needs to be ignored (see the appendix for ID information), for example, you want to ignoreindentation contains mixed spaces and tabsFor this warning, just add its ID:E101 Just

    Appendix: All warning messages and corresponding IDs, official address: https://pep8.readthedocs.io/en/latest/intro.html#error-codes

    code sample message
    E1 Indentation
    E101 indentation contains mixed spaces and tabs
    E111 indentation is not a multiple of four
    E112 expected an indented block
    E113 unexpected indentation
    E114 indentation is not a multiple of four (comment)
    E115 expected an indented block (comment)
    E116 unexpected indentation (comment)
    E117 over-indented
    E121 (*^) continuation line under-indented for hanging indent
    E122 (^) continuation line missing indentation or outdented
    E123 (*) closing bracket does not match indentation of opening bracket’s line
    E124 (^) closing bracket does not match visual indentation
    E125 (^) continuation line with same indent as next logical line
    E126 (*^) continuation line over-indented for hanging indent
    E127 (^) continuation line over-indented for visual indent
    E128 (^) continuation line under-indented for visual indent
    E129 (^) visually indented line with same indent as next logical line
    E131 (^) continuation line unaligned for hanging indent
    E133 (*) closing bracket is missing indentation
    E2 Whitespace
    E201 whitespace after ‘(‘
    E202 whitespace before ‘)’
    E203 whitespace before ‘:’
    E211 whitespace before ‘(‘
    E221 multiple spaces before operator
    E222 multiple spaces after operator
    E223 tab before operator
    E224 tab after operator
    E225 missing whitespace around operator
    E226 (*) missing whitespace around arithmetic operator
    E227 missing whitespace around bitwise or shift operator
    E228 missing whitespace around modulo operator
    E231 missing whitespace after ‘,’, ‘;’, or ‘:’
    E241 (*) multiple spaces after ‘,’
    E242 (*) tab after ‘,’
    E251 unexpected spaces around keyword / parameter equals
    E261 at least two spaces before inline comment
    E262 inline comment should start with ‘# ‘
    E265 block comment should start with ‘# ‘
    E266 too many leading ‘#’ for block comment
    E271 multiple spaces after keyword
    E272 multiple spaces before keyword
    E273 tab after keyword
    E274 tab before keyword
    E275 missing whitespace after keyword
    E3 Blank line
    E301 expected 1 blank line, found 0
    E302 expected 2 blank lines, found 0
    E303 too many blank lines (3)
    E304 blank lines found after function decorator
    E305 expected 2 blank lines after end of function or class
    E306 expected 1 blank line before a nested definition
    E4 Import
    E401 multiple imports on one line
    E402 module level import not at top of file
    E5 Line length
    E501 (^) line too long (82 > 79 characters)
    E502 the backslash is redundant between brackets
    E7 Statement
    E701 multiple statements on one line (colon)
    E702 multiple statements on one line (semicolon)
    E703 statement ends with a semicolon
    E704 (*) multiple statements on one line (def)
    E711 (^) comparison to None should be ‘if cond is None:’
    E712 (^) comparison to True should be ‘if cond is True:’ or ‘if cond:’
    E713 test for membership should be ‘not in’
    E714 test for object identity should be ‘is not’
    E721 (^) do not compare types, use ‘isinstance()’
    E722 do not use bare except, specify exception instead
    E731 do not assign a lambda expression, use a def
    E741 do not use variables named ‘l’, ‘O’, or ‘I’
    E742 do not define classes named ‘l’, ‘O’, or ‘I’
    E743 do not define functions named ‘l’, ‘O’, or ‘I’
    E9 Runtime
    E901 SyntaxError or IndentationError
    E902 IOError
    W1 Indentation warning
    W191 indentation contains tabs
    W2 Whitespace warning
    W291 trailing whitespace
    W292 no newline at end of file
    W293 blank line contains whitespace
    W3 Blank line warning
    W391 blank line at end of file
    W5 Line break warning
    W503 (*) line break before binary operator
    W504 (*) line break after binary operator
    W505 (*^) doc line too long (82 > 79 characters)
    W6 Deprecation warning
    W601 .has_key() is deprecated, use ‘in’
    W602 deprecated form of raising exception
    W603 ‘<>’ is deprecated, use ‘!=’
    W604 backticks are deprecated, use ‘repr()’
    W605 invalid escape sequence ‘x’
    W606 ‘async’ and ‘await’ are reserved keywords starting with Python 3.7

    Я использую flake8 в Visual Studio Code, пишу код с помощью Аннотации переменных Python 3.6. Пока все работало без проблем, но я столкнулся со странным предупреждением.

    Это отлично работает:

    style: str = """
    width: 100%;
    ...
    """
    # Doing sth with `style`
    

    Это тоже:

    img_style: str = """
    width: 100%;
    ...
    """
    # Doing sth with `img_style`
    

    Однако это не так, это приводит к предупреждению ниже:

    iframe_style: str = """
    width: 100%;
    ...
    """
    # Doing sth with `iframe_style`
    

    flake8 warning

    Что ж, технически это работает нормально; код работает. Но почему-то flake8 это не устраивает. Многострочная строка и следующий за ней код всегда одинаковы.

    Когда я опускаю букву «f» (i_rame_style), я тоже не получаю предупреждения! Так что, я думаю, по какой-то причине flake8 думает о if foo: bar() здесь !?

    Что мне здесь не хватает? Это ошибка в flake8?

    1 ответ

    Лучший ответ

    Изменить: проблема в pycodestyle (pep8), который вызывается flake8. Остальные по-прежнему в силе.

    Второе изменение: я провел дополнительное исследование, и проблема исправлена ​​здесь. Однако исправление еще не выпущено.

    Для меня это определенно похоже на ошибку flake8:

    flakebug.py:

    innocuous: str = ""
    ifstarting_string: str = ""
    forfalse_positivetoo: str = ""
    whilethis_lookslikeabug: str = ""
    elsehaha: str = ""
    

    В оболочке:

    $ # python3.6 -m pycodestyle flakebug.py gives the same results
    $ python3.6 -m flake8 flakebug.py 
    flakebug.py:2:18: E701 multiple statements on one line (colon)
    flakebug.py:3:21: E701 multiple statements on one line (colon)
    flakebug.py:4:24: E701 multiple statements on one line (colon)
    flakebug.py:5:9: E701 multiple statements on one line (colon)
    

    Похоже, что каждая строка, начинающаяся с оператора потока управления, запускает его. Держу пари, что здесь используется регулярное выражение вроде (if|else|while|for).*:.

    Я постараюсь разобраться в этом и обновить этот ответ, если смогу, а пока вы можете добавить несколько аннотаций # noqa, и все будет готово :)


    10

    etene
    11 Апр 2018 в 15:26

    Like this post? Please share to your friends:
  • Как найти повтор в таблице excel
  • Как найти свой мастер пароль
  • Как найти брокера для форекс
  • Как в планшете найти диспетчер загрузок
  • Резидент эвил 2 тайное убежище как найти