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

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...

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,1834 gold badges29 silver badges74 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

By Szymon Lipiński

May 21, 2013

When you develop a program in a group of programmers, it is really important to have some standards. Especially helpful are standards of naming things and formatting code. If all team members format the code in the same way and use consistent names, then it is much easier to read the code. This also means that the team works faster.

The same rules apply when you develop software in Python.

For Python there is a document which describes some of the most desirable style features for Python code Style Guide for Python Code. However there are some problems with that, as even the standard Python library has some libraries which are not consistent. This shouldn’t be an excuse for your team to be inconsistent as well. Ensuring that the code is nice and readable is worth working for a moment on that.

In Python there are two tools which I use for writing code in Python—​Python style guide checker and Python code static checker.

pep8

Program pep8 is a simple tool checking Python code against some of the style conventions in PEP 8 document.

Installation

You can install it within your virtual environment with simple:

pip install pep8

Usage

Let’s test the pep8 command on such an ugly Python file named test.py:

"this is a very long comment line this is a very long comment line this is a very long comment line"
def sth  (  a ):
    return  "x"+a
def sth1 ( a,b,c):
    a+b+c

The basic usage of the program is:

pep8 test.py

The above command prints:

test.py:1:80: E501 line too long (100 > 79 characters)
test.py:2:1: E302 expected 2 blank lines, found 0
test.py:2:11: E201 whitespace after '('
test.py:2:14: E202 whitespace before ')'
test.py:2:8: E211 whitespace before '('
test.py:3:16: E225 missing whitespace around operator
test.py:4:1: E302 expected 2 blank lines, found 0
test.py:4:11: E201 whitespace after '('
test.py:4:13: E231 missing whitespace after ','
test.py:4:15: E231 missing whitespace after ','
test.py:4:9: E211 whitespace before '('
test.py:5:6: E225 missing whitespace around operator
test.py:5:8: E225 missing whitespace around operator
test.py:6:1: W391 blank line at end of file

Configuration

Pep8 is highly configurable. The most important options allow to choose which errors should be ignored. For this there is an argument –ignore. There is also one thing in PEP8 document, which I don’t agree with. This document states that the length of the line shouldn’t be bigger than 80 characters. Usually terminals and editors I use are much wider and having 100 characters doesn’t make your program unreadable. You can set the allowed length of your line with –max-line-length.

So if I want to ignore the errors about empty lines at the end of file and set maximum line length to 100, then the whole customized command is:

pep8 --ignore=W391 --max-line-length=100  test.py

The output is different now:

test.py:2:1: E302 expected 2 blank lines, found 0
test.py:2:11: E201 whitespace after '('
test.py:2:14: E202 whitespace before ')'
test.py:2:8: E211 whitespace before '('
test.py:3:16: E225 missing whitespace around operator
test.py:4:1: E302 expected 2 blank lines, found 0
test.py:4:11: E201 whitespace after '('
test.py:4:13: E231 missing whitespace after ','
test.py:4:15: E231 missing whitespace after ','
test.py:4:9: E211 whitespace before '('
test.py:5:6: E225 missing whitespace around operator
test.py:5:8: E225 missing whitespace around operator
Config file

The same effect can be achieved using a config file. PEP8 searches for this file at the project level, the file must be named .pep8 or setup.cfg. If such a file is not found, then it looks for a file ~/.config/pep8. Only the first file is taken into consideration. After finding a file, it looks for a pep8 section in, if there is no such section, then no custom settings are used.

To have the same settings as in the above example, you can create a file .pep8 in the project directory with the following content:

[pep8]
ignore = W391
max-line-length = 100

The list of all all possible errors you can find at PEP8 documentation page.

Statistics

Another nice option which I use for checking the code is –statistics. It prints information about the type and number of problems found. I use it along with -qq option which causes pep8 to hide all other informations. The sort -n 1 -k -r part sorts the pep8 output in reverse order (biggest numbers come first) by first column treating that as numbers:

pep8 --statistics -qq django | sort -k 1 -n -r

The first 10 lines of the above command run against Django 1.5.1 code look like:

4685    E501 line too long (80 > 79 characters)
1718    E302 expected 2 blank lines, found 1
1092    E128 continuation line under-indented for visual indent
559     E203 whitespace before ':'
414     E231 missing whitespace after ','
364     E261 at least two spaces before inline comment
310     E251 no spaces around keyword / parameter equals
303     E701 multiple statements on one line (colon)
296     W291 trailing whitespace
221     E225 missing whitespace around operator

pylint

Pylint is a program very similar to pep8, it just checks different things. The pylint’s goal is to look for common errors in programs and find potential code smells.

Installation

You can install pylint in a similar way as pep8:

pip install pylint

Usage

Usage is similar as well:

pylint --reports=n test.py

Notice there is –reports argument. Without it, the output is much longer and quiet messy.

The output of the above command is:

No config file found, using default configuration
************* Module test
C:  1,0: Line too long (100/80)
C:  2,0:sth: Invalid name "a" for type argument (should match [a-z_][a-z0-9_]{2,30}$)
C:  2,0:sth: Missing docstring
C:  2,12:sth: Invalid name "a" for type variable (should match [a-z_][a-z0-9_]{2,30}$)
C:  4,0:sth1: Comma not followed by a space
def sth1 ( a,b,c):
            ^^
C:  4,0:sth1: Invalid name "a" for type argument (should match [a-z_][a-z0-9_]{2,30}$)
C:  4,0:sth1: Invalid name "b" for type argument (should match [a-z_][a-z0-9_]{2,30}$)
C:  4,0:sth1: Invalid name "c" for type argument (should match [a-z_][a-z0-9_]{2,30}$)
C:  4,0:sth1: Missing docstring
C:  4,11:sth1: Invalid name "a" for type variable (should match [a-z_][a-z0-9_]{2,30}$)
C:  4,13:sth1: Invalid name "b" for type variable (should match [a-z_][a-z0-9_]{2,30}$)
C:  4,15:sth1: Invalid name "c" for type variable (should match [a-z_][a-z0-9_]{2,30}$)
W:  5,4:sth1: Statement seems to have no effect

Configuration

For pylint you can decide which problems should be ignored as well. If I want to ignore some errors, you have to know its number first. You can get the number in two ways, you can check at pylint errors list or add the message number with argument –include-ids=y:

pylint --reports=n --include-ids=y test.py
No config file found, using default configuration
************* Module test
C0301:  1,0: Line too long (100/80)
C0103:  2,0:sth: Invalid name "a" for type argument (should match [a-z_][a-z0-9_]{2,30}$)
C0111:  2,0:sth: Missing docstring
C0103:  2,12:sth: Invalid name "a" for type variable (should match [a-z_][a-z0-9_]{2,30}$)
C0324:  4,0:sth1: Comma not followed by a space
def sth1 ( a,b,c):
            ^^
C0103:  4,0:sth1: Invalid name "a" for type argument (should match [a-z_][a-z0-9_]{2,30}$)
C0103:  4,0:sth1: Invalid name "b" for type argument (should match [a-z_][a-z0-9_]{2,30}$)
C0103:  4,0:sth1: Invalid name "c" for type argument (should match [a-z_][a-z0-9_]{2,30}$)
C0111:  4,0:sth1: Missing docstring
C0103:  4,11:sth1: Invalid name "a" for type variable (should match [a-z_][a-z0-9_]{2,30}$)
C0103:  4,13:sth1: Invalid name "b" for type variable (should match [a-z_][a-z0-9_]{2,30}$)
C0103:  4,15:sth1: Invalid name "c" for type variable (should match [a-z_][a-z0-9_]{2,30}$)
W0104:  5,4:sth1: Statement seems to have no effect

Now I know the number of the problem I want to ignore, let’s assume it is C0103, then I can ignore it with:

pylint --reports=n --include-ids=y --disable=C0103 test.py
No config file found, using default configuration
************* Module test
C0301:  1,0: Line too long (100/80)
C0111:  2,0:sth: Missing docstring
C0324:  4,0:sth1: Comma not followed by a space
def sth1 ( a,b,c):
            ^^
C0111:  4,0:sth1: Missing docstring
W0104:  5,4:sth1: Statement seems to have no effect
Config file

Pylint also supports setting the options in a config file. This config file can be a little bit complicated, and I think the best way is to let pylint generate the file, this can be done with the –generate-rcfile argument:

pylint --reports=n --include-ids=y --disable=C0103 --generate-rcfile > .pylint

This will create config file with all default settings and the changes from the command line.

To use the new config file, you should use the –rcfile argument:

pylint --rcfile=.pylint test.py

Pylint is great—​sometimes even too great.

I usually ignore many of the errors, as too often the changes needed to satisfy pylint are not worth time spending on them. One of common problems found by pylint is that the variable name is too short. It has a rule that all the names should have between 2 and 30 characters. There is nothing bad with one letter variable, especially when it is something like Point(x, y) or it is a small local variable, something like for i in xrange(1,1000).

However on the other hand when a variable has much broader usage, or it should have some meaningful name to have code easier to read, it is a good idea to change the code.

For me it is good to have pylint checking such errors, so I don’t want pylint to ignore them. Sometimes it is OK to have code which violates those rules, so I just ignore them after ensuring that it is on purpose.

python


PEP8¶

PEP8 is the official style guide for python. It is important to know the style-guide if you want to be a part of the python-community.

PEP8 coding conventions are:
  • Spaces are the preferred indentation method.
  • Use 4 spaces per indentation level.
  • Limit all lines to a maximum of 79 characters.
  • Separate top-level function and class definitions with two blank lines.
  • Method definitions inside a class are surrounded by a single blank line.
  • Imports should be grouped in the following order:
    • Standard library imports.
    • Related third party imports.
    • Local application/library specific imports.
    • A blank line between each group of imports.

pycodestyle¶

Pycodestyle (Formerly PEP8) is the official linter tool to check the python code against the style conventions of PEP8 python.

To install it:
pip install pycodestyle.

Let us take a small example script to test pycodestyle

We will create a test script file test_script.py and use it as an example for all the linters.

from __future__ import print_function
import os, sys
import logging
from .. import views

class DoSomething(SomeCommand) :

    def __init__(self):
        for i in range(1,11):
            if self.number == i:
                print("matched")
            else:
                print('not matched')

    def check_user(self):
        if self.user: return True
        else  : return False

If we run pycodestyle:
$ pycodestyle {source_file_or_directory}

$ pycodestyle test_script.py
test_script.py:2:10: E401 multiple imports on one line
test_script.py:6:1: E302 expected 2 blank lines, found 1
test_script.py:6:31: E203 whitespace before ':'
test_script.py:9:25: E231 missing whitespace after ','
test_script.py:13:37: W291 trailing whitespace
test_script.py:16:21: E701 multiple statements on one line (colon)
test_script.py:16:34: W291 trailing whitespace
test_script.py:17:13: E271 multiple spaces after keyword
test_script.py:17:14: E203 whitespace before ':'
test_script.py:17:15: E701 multiple statements on one line (colon)
test_script.py:17:29: W291 trailing whitespace

To see the summary, use --statistics -qq
$ pycodestyle --statistics -qq {source_file_or_directory}

$ pycodestyle --statistics -qq test_script.py
    2       E203 whitespace before ':'
    1       E231 missing whitespace after ','
    1       E271 multiple spaces after keyword
    1       E302 expected 2 blank lines, found 1
    1       E401 multiple imports on one line
    2       E701 multiple statements on one line (colon)
    3       W291 trailing whitespace

We can also make pycodestyle show the error and the description of how to solve the error by using --show-source --show-pep8

$ pycodestyle --show-source --show-pep8 {source_file_or_directory}

$ pycodestyle --show-source --show-pep8  test_script.py
test_script.py:2:10: E401 multiple imports on one line
import os, sys
        ^
    Place imports on separate lines.
    ...
    ...
    ...

To customise pycodestyle we can configure it at the project-level or in user-level.
It is better to configure at the project level as the style usually varies for every-project.

To configure a project’s pycodestyle create a tox.ini Or a setup.cfg

And add

[pycodestyle]
ignore = E501, W291
max-line-length = 88
statistics = True
In the above file ,
  • [pycodestyle] tells this is the pycodestyle section
  • we are telling to ignore the Error E501 (which is a line-length error) and Warning W291 (trailing whitespace warning).
  • mentioning the max-line-length to be 88.
  • and to show the statistics with every check
PEP8 Error/Warning code

Error/ Warning Meaning
Starting with E… Errors
Starting with W… Warnings
100 type … Indentation
200 type … Whitespace
300 type … Blank lines
400 type … Imports
500 type … Line length
600 type … Deprecation
700 type … Statements
900 type … Syntax errors

pylint¶

Pylint is a python linter which checks the source code and also acts as a bug and quality checker. It has more verification checks and options than just PEP8(Python style guide).

This is the most commonly used tool for linting in python.

It includes the following features:
  • Checking the length of each line
  • Checking if variable names are well-formed according to the project’s coding standard
  • Checking if declared interfaces are truly implemented.

To install it:
pip install pylint.

Usage:
pylint {source_file_or_directory}

Using the file test_script.py as an example

$ pylint test_script.py
No config file found, using default configuration
************* Module test_script
C:  6, 0: No space allowed before :
class DoSomething(SomeCommand) :
                            ^ (bad-whitespace)
C:  9, 0: Exactly one space required after comma
        for i in range(1,11):
                        ^ (bad-whitespace)
C: 13, 0: Trailing whitespace (trailing-whitespace)
C: 16, 0: Trailing whitespace (trailing-whitespace)
C: 17, 0: Final newline missing (missing-final-newline)
C: 17, 0: No space allowed before :
        else  : return False
            ^ (bad-whitespace)
C:  1, 0: Missing module docstring (missing-docstring)
C:  2, 0: Multiple imports on one line (os, sys) (multiple-imports)
E:  4, 0: Attempted relative import beyond top-level package (relative-beyond-top-level)
C:  6, 0: Missing class docstring (missing-docstring)
E:  6,18: Undefined variable 'SomeCommand' (undefined-variable)
C: 15, 4: Missing method docstring (missing-docstring)
R: 16, 8: The if statement can be replaced with 'return bool(test)' (simplifiable-if-statement)
R: 16, 8: Unnecessary "else" after "return" (no-else-return)
C: 16,22: More than one statement on a single line (multiple-statements)
R:  6, 0: Too few public methods (1/2) (too-few-public-methods)
W:  2, 0: Unused import sys (unused-import)
W:  2, 0: Unused import os (unused-import)
W:  3, 0: Unused import logging (unused-import)
W:  4, 0: Unused import views (unused-import)

----------------------------------------------------------------------
Your code has been rated at -10.00/10 (previous run: -10.00/10, +0.00)

As we can see pylint has more error/warning checks and options than pep8. And it is more descriptive.

To customise pylint we can configure it at the project-level, user-level or global-level .

  • create a /etc/pylintrc for default global configuration
  • create a ~/pylintrc for default user configuration
  • Or create a pylintrc file

To create a pylintrc file pylint --generate-rcfile > pylintrc , which creates a template pylintrc(with comments) which can be customised as required.

For example if we want the max line lenght to be 88, then we have to set the max-line-length to 88 .

pyflakes¶

pyflakes is a verification tool(linter) which checks for Python files for errors.
Pyflakes doesn’t verify the style at all but it verifies only logistic errors like the syntax tree of each file individually.

To install it:
pip install pyflakes.

Let us take the same example script to test pyflakes

Usage:
pyflakes {source_file_or_directory}

Using the file test_script.py as an example

$ pyflakes test_script.py
test_script.py:2: 'sys' imported but unused
test_script.py:2: 'os' imported but unused
test_script.py:3: 'logging' imported but unused
test_script.py:4: '..views' imported but unused
test_script.py:6: undefined name 'SomeCommand'

It detected newly “library imported but unused” and “Undefined name”, it doesn’t verify the style but verify only logistic error.

If we like Pyflakes but also want stylistic checks, we can use flake8, which combines Pyflakes with style checks against PEP 8

flake8¶

Flake8 is just a wrapper around pyflakes, pycodestyle and McCabe script (circular complexity checker) (which is used to detect complex-code).

If we like Pyflakes but also want stylistic checks, we can use flake8, which combines Pyflakes with style checks against PEP 8

To install it:
pip install flake8.

Usage:
flake8 {source_file_or_directory}

To get statics also
flake8 {source_file_or_directory} --statistics

Using the file test_script.py as an example

$ flake8 test_script.py --statistics
test_script.py:2:1: F401 'os' imported but unused
test_script.py:2:1: F401 'sys' imported but unused
test_script.py:2:10: E401 multiple imports on one line
test_script.py:3:1: F401 'logging' imported but unused
test_script.py:4:1: F401 '..views' imported but unused
test_script.py:6:1: E302 expected 2 blank lines, found 1
test_script.py:6:19: F821 undefined name 'SomeCommand'
test_script.py:6:31: E203 whitespace before ':'
test_script.py:9:25: E231 missing whitespace after ','test_script.py:13:37: W291 trailing whitespace
test_script.py:16:21: E701 multiple statements on one line (colon)
test_script.py:16:34: W291 trailing whitespace
test_script.py:17:13: E271 multiple spaces after keyword
test_script.py:17:14: E203 whitespace before ':'
test_script.py:17:15: E701 multiple statements on one line (colon)test_script.py:17:29: W291 trailing whitespace
2     E203 whitespace before ':'
1     E231 missing whitespace after ','
1     E271 multiple spaces after keyword
1     E302 expected 2 blank lines, found 1
1     E401 multiple imports on one line
2     E701 multiple statements on one line (colon)
4     F401 'os' imported but unused
1     F821 undefined name 'SomeCommand'
3     W291 trailing whitespace

The output is formatted as:

file path : line number : column number : error code : short description

By adding the --show-source option, it’ll be easier to find out what parts of the source code need to be revised.

$ flake8 test_script.py  --show-source
test_script.py:2:1: F401 'os' imported but unused
import os, sys
^
test_script.py:2:1: F401 'sys' imported but unused
import os, sys
^
test_script.py:2:10: E401 multiple imports on one line
import os, sys
        ^
test_script.py:3:1: F401 'logging' imported but unused
import logging
^
...
...
...

We can see the result of pep8 (error code is Exxx and Wxxx) and pyflakes (error code is Fxxx) are output together.

Flake8 Error code meaning

The error code of flake8 are :

  • E***/W***: Errors and warnings of pep8
  • F***: Detections of PyFlakes
  • C9**: Detections of circulate complexity by McCabe-script

Flake8 can be customised/configured in :

  • Toplevel User directory, in ~/.config/flake8 Or
  • In a project folder by one of setup.cfg, tox.ini, or .flake8.

To customize flake8

[flake8]
ignore = D203
exclude = .git,__pycache__,docs/source/conf.py,old,build,dist, *migrations*
max-complexity = 10

This is same as the below one line command

$ flake8 --ignore D203 
     --exclude .git,__pycache__,docs/source/conf.py,old,build,dist 
     --max-complexity 10

black¶

black is a python code auto-formatter.
Black reformats entire files in place and also formats the strings to have double-qoutes.

Black is not configurable(except for line-length).

To install it:
pip install black.

Usage:
black {source_file_or_directory}

The response we got when we did black test_script.py is

_images/black-formatter.png

Using the file test_script.py as an example

And the formatted code is

from __future__ import print_function
import os, sys
import logging
from .. import views


class DoSomething(SomeCommand):
    def __init__(self):
        for i in range(1, 11):
            if self.number == i:
                print("matched")
            else:
                print("not matched")

    def check_user(self):
        if self.user:
            return True
        else:
            return False

To customise black we have to add this section in pyproject.toml

[tool.black]
line-length = 90
py36 = true
include = '.pyi?$'
exclude = '''
/(
    .git
| .mypy_cache
| .tox
| .venv
| _build
| buck-out
| build
| dist
)/
'''

In the above section, we have modified the line-lenght to 90,
and specified the python version to 3.6

autopep8¶

autopep8 automatically formats Python code to the PEP8 style. It fixes most of the formatting issues that are reported by pycodestyle.

To install it:
pip install autopep8

Usage(to format a file):
autopep8 --in-place {file_name}

here --in-place is to make changes to files in place.

Using the file test_script.py as an example

This is the formatted code.

from __future__ import print_function
import os
import sys
import logging
from .. import views


class DoSomething(SomeCommand):

    def __init__(self):
        for i in range(1, 11):
            if self.number == i:
                print("matched")
            else:
                print('not matched')

    def check_user(self):
        if self.user:
            return True
        else:
            return False

To configure autopep8 we have to add this section [pep8] in setup.cfg :

[pep8]
ignore = E226,E302,E41
max-line-length = 160

yapf¶

Yet another Python formatter is another auto-formatter which is maintained by google.
yapf is highly configurable and it has different base configurations, like pep8, Google and Facebook.

To install it:
pip install yapf

Usage:
yapf -i {source_file_or_directory}

here -i is to make changes to files in place.

This is the formatted code.

from __future__ import print_function
import os, sys
import logging
from .. import views


class DoSomething(SomeCommand):
    def __init__(self):
        for i in range(1, 11):
            if self.number == i:
                print("matched")
            else:
                print('not matched')

    def check_user(self):
        if self.user: return True
        else: return False

To configure yapf we have to add this section [yapf] in setup.cfg :

[yapf]
ignore = E226,E302
max-line-length = 96

Conclusion¶

Linting:

Pylint and flake8 have the most detailed way of showing the error and warnings(and it also gives the code rating).

Изменение: проблема заключается в 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 и вы будете установлены :)

Я использую 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

flake8 is static analyzer (aka. linter) for Python that helps you enforce coding standards and even to find potential bugs.
It can report issues with you code ranging from simple issues such as not including a space around an arithmetic operator (writing a+b vs. a + b) to
issues such as redefining a function which, if done by mistake can be the source of a hard-to-detect bug.

A great way to improve your Python project is to configure your CI-system to run flake8 every time you push out code to ensure your code does not start to accumulate such issues.

How can you get started with flake8 on an already existing project?

Install flake8

first you need to install flake8 and I recommend at least the pylint plugin as well:

pip install flake8 flake8-pylint

First run of flake8

Then cd to the root of your project and run

flake8 .

This will probably spew hundreds or thousands of failures which would be overwhelming to fix.

So instead of that I wrote a small script called flake8-start that will create a .flake8 configuration
file for your project ignoring every rule-violation currently existing in your code-base.

The file looks like this:

# E226 - (9) - missing whitespace around arithmetic operator
# E265 - (7) - block comment should start with '# '
# E305 - (1) - expected 2 blank lines after class or function definition, found 1
# E501 - (4) - line too long (108 > 79 characters)
# W391 - (1) - blank line at end of file
# PLE0102 - (2) - function already defined line 1 (function-redefined)


[flake8]
ignore =
    *.py E226 E265 E305 E501 W391 PLE0102

The first part of this file is the list of rules your currently is violating (E265 is just some ID code), followed by the number of issues found in your code-base,
followed by the report text the first time the violation appeared. This list was added for your convenience so later when you start to clean up your code it would be
easier for you to know which code means what. Without the need to look it up on some web-site.

The number of occurrences can help you get some feeling of how much work it might be to fix that type of an issue.

Setting up your CI to run with this configuration file will already help you ensure that no new type of problem will enter your code-base.

For example on GitHub you can create a file called .github/workflows/ci.yml with the following content:

name: CI

on: [push, pull_request]

jobs:
  flake-job:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
    name: Flake8
    steps:
      - uses: actions/checkout@v2

      - name: Set up Python
        uses: actions/setup-python@v2
        with:
          python-version: 3.9

      - name: Install deps
        run: |
          python --version
          pip install -r requirements.txt
          pip install flake8 flake8-pylint

      - name: Run flake8
        run: |
            flake8 .

This will run flake8 every time you push out code.

Cleanup

Then comes the cleanup. I usually do this one step a time to improve the code.

  • Review the failures listed as comments in the .flake8 file.
  • Pick one of them that you feel is important to fix.
  • Remove its code from the ignore list.
  • Run `flake8` on your code to see where is this failure reported.
  • Fix the code. (The best would be to make sure you have test executing that area of the code before you make the change, but if you are brave you can also make the changes without tests.)
  • Now that this failure-type does not appear in your code any more you can also remove the comment explaining it from the .flake8 file.
  • Commit your new version of the code and the updated `.flake8` file that does not ignore this error-type any more.

Repeat this process with every failure type you feel need to be fixed.

Special cases

There might be rules that you would like to follow generally, but in a few special cases you might need to violate them in your code.
There are various ways to tell flake8 to disregard specific violations. I won’t describe them here. At least not till next time.

List of code

  • B001 — Do not use bare `except:`, it also catches unexpected events like memory errors, interrupts, system exit, and so on. Prefer `except Exception:`. If you’re sure what you’re doing, be explicit and write `except BaseException:`.
  • B005 — Using .strip() with multi-character strings is misleading the reader. It looks like stripping a substring. Move your character set to a constant if this is deliberate. Use .replace() or regular expressions to remove string fragments.
  • B006 — Do not use mutable data structures for argument defaults. They are created during function definition time. All calls to the function reuse this one instance of that data structure, persisting changes between them.
  • B007 — Loop control variable ‘class’ not used within the loop body. If this is intended, start the name with an underscore.
  • B015 — Pointless comparison. This comparison does nothing but waste CPU instructions. Either prepend `assert` or remove it.
  • E111 — indentation is not a multiple of 4
  • E114 — indentation is not a multiple of 4 (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
  • E131 — continuation line unaligned for hanging indent
  • E201 — whitespace after ‘{‘
  • E202 — whitespace before ‘)’
  • E203 — whitespace before ‘:’
  • E221 — multiple spaces before operator
  • E222 — multiple spaces 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 ‘:’
  • E241 — multiple spaces after ‘,’
  • E251 — unexpected spaces around keyword / parameter equals
  • E252 — missing whitespace around 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
  • E301 — expected 1 blank line, found 0
  • E302 — expected 2 blank lines, found 1
  • E303 — too many blank lines (3)
  • E305 — expected 2 blank lines after class or function definition, found 1
  • E306 — expected 1 blank line before a nested definition, found 0
  • E401 — multiple imports on one line
  • E402 — module level import not at top of file
  • E501 — line too long (95 > 79 characters)
  • 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 False should be ‘if cond is False:’ or ‘if not cond:’
  • E713 — test for membership should be ‘not in’
  • E714 — test for object identity should be ‘is not’
  • E722 — do not use bare ‘except’
  • E741 — ambiguous variable name ‘l’
  • E999 — SyntaxError: invalid syntax
  • F401 — ‘sqlite3’ imported but unused
  • F403 — ‘from Application import *’ used; unable to detect undefined names
  • F405 — ‘get_data’ may be undefined, or defined from star imports:a Application
  • F541 — f-string is missing placeholders
  • F811 — redefinition of unused ‘model’ from line 134
  • F821 — undefined name ‘metadata’
  • F841 — local variable ‘thumbnails’ is assigned to but never used
  • PLC0103 — Module name «Application» doesn’t conform to snake_case naming style (invalid-name)
  • PLC0113 — Consider changing «not ‘/app’ in sys.path» to «‘/app’ not in sys.path» (unneeded-not)
  • PLC0114 — Missing module docstring (missing-module-docstring)
  • PLC0115 — Missing class docstring (missing-class-docstring)
  • PLC0116 — Missing function or method docstring (missing-function-docstring)
  • PLC0121 — Comparison ‘target_path == None’ should be ‘target_path is None’ (singleton-comparison)
  • PLC0123 — Use isinstance() rather than type() for a typecheck. (unidiomatic-typecheck)
  • PLC0201 — Consider iterating the dictionary directly instead of calling .keys() (consider-iterating-dictionary)
  • PLC0206 — Consider iterating with .items() (consider-using-dict-items)
  • PLC0207 — Use hashname.rsplit(‘images/’, maxsplit=1)[-1] instead (use-maxsplit-arg)
  • PLC0209 — Formatting a regular string which could be a f-string (consider-using-f-string)
  • PLC0301 — Line too long (104/100) (line-too-long)
  • PLC0302 — Too many lines in module (1055/1000) (too-many-lines)
  • PLC0303 — Trailing whitespace (trailing-whitespace)
  • PLC0304 — Final newline missing (missing-final-newline)
  • PLC0305 — Trailing newlines (trailing-newlines)
  • PLC0321 — More than one statement on a single line (multiple-statements)
  • PLC0325 — Unnecessary parens after ‘not’ keyword (superfluous-parens)
  • PLC0410 — Multiple imports on one line (string, random) (multiple-imports)
  • PLC0411 — standard import «import os» should be placed before «from Application import DB_FILE» (wrong-import-order)
  • PLC0412 — Imports from package Application are not grouped (ungrouped-imports)
  • PLC0413 — Import «from pymongo import MongoClient, UpdateOne» should be placed at the top of the module (wrong-import-position)
  • PLC0415 — Import outside toplevel (random.seed, random.sample) (import-outside-toplevel)
  • PLE0102 — function already defined line 6 (function-redefined)
  • PLE0203 — Access to member ‘tm’ before its definition line 362 (access-member-before-definition)
  • PLE0401 — Unable to import ‘pymongo’ (import-error)
  • PLE0601 — Using variable ‘src’ before assignment (used-before-assignment)
  • PLE0602 — Undefined variable ‘get_imagedb_dim_reduction’ (undefined-variable)
  • PLE0611 — No name ‘models’ in module ‘LazyLoader’ (no-name-in-module)
  • PLE1101 — Module ‘cv2’ has no ‘imread’ member (no-member)
  • PLE1111 — Assigning result of a function call, where the function has no return (assignment-from-no-return)
  • PLE1121 — Too many positional arguments for function call (too-many-function-args)
  • PLE1123 — Unexpected keyword argument ‘reading_only’ in function call (unexpected-keyword-arg)
  • PLE1124 — Argument ‘query’ passed by position and keyword in function call (redundant-keyword-arg)
  • PLE1130 — bad operand type for unary +: str (invalid-unary-operand-type)
  • PLR0201 — Method could be a function (no-self-use)
  • PLR0205 — Class ‘FileLock’ inherits from object, can be safely removed from bases in python3 (useless-object-inheritance)
  • PLR0206 — Cannot have defined parameters for properties (property-with-parameters)
  • PLR0902 — Too many instance attributes (22/7) (too-many-instance-attributes)
  • PLR0903 — Too few public methods (1/2) (too-few-public-methods)
  • PLR0911 — Too many return statements (7/6) (too-many-return-statements)
  • PLR0912 — Too many branches (20/12) (too-many-branches)
  • PLR0913 — Too many arguments (6/5) (too-many-arguments)
  • PLR0914 — Too many local variables (18/15) (too-many-locals)
  • PLR0915 — Too many statements (65/50) (too-many-statements)
  • PLR1705 — Unnecessary «else» after «return» (no-else-return)
  • PLR1707 — Disallow trailing comma tuple (trailing-comma-tuple)
  • PLR1710 — Either all return statements in a function should return an expression, or none of them should. (inconsistent-return-statements)
  • PLR1711 — Useless return at end of function or method (useless-return)
  • PLR1716 — Simplify chained comparison between the operands (chained-comparison)
  • PLR1718 — Consider using a set comprehension (consider-using-set-comprehension)
  • PLR1721 — Unnecessary use of a comprehension, use list(pool.starmap(analyze_image_status, paths)) instead. (unnecessary-comprehension)
  • PLR1725 — Consider using Python 3 style super() without arguments (super-with-arguments)
  • PLR1731 — Consider using ‘current_image = max(current_image, 0)’ instead of unnecessary if block (consider-using-max-builtin)
  • PLR1732 — Consider using ‘with’ for resource-allocating operations (consider-using-with)
  • PLW0101 — Unreachable code (unreachable)
  • PLW0102 — Dangerous default value [] as argument (dangerous-default-value)
  • PLW0104 — Statement seems to have no effect (pointless-statement)
  • PLW0105 — String statement has no effect (pointless-string-statement)
  • PLW0106 — Expression «im — cv2.cvtColor(im, cv2.COLOR_BGR2RGB) / 255.0» is assigned to nothing (expression-not-assigned)
  • PLW0107 — Unnecessary pass statement (unnecessary-pass)
  • PLW0122 — Use of exec (exec-used)
  • PLW0123 — Use of eval (eval-used)
  • PLW0125 — Using a conditional statement with a constant value (using-constant-test)
  • PLW0143 — Comparing against a callable, did you omit the parenthesis? (comparison-with-callable)
  • PLW0201 — Attribute ‘affinity_matrix_’ defined outside __init__ (attribute-defined-outside-init)
  • PLW0221 — Variadics removed in overridden ‘Sampling.call’ method (arguments-differ)
  • PLW0238 — Unused private member `dataset_viewer_tag.__VAR__observer` (unused-private-member)
  • PLW0301 — Unnecessary semicolon (unnecessary-semicolon)
  • PLW0311 — Bad indentation. Found 24 spaces, expected 20 (bad-indentation)
  • PLW0401 — Wildcard import Application (wildcard-import)
  • PLW0404 — Reimport ‘seed’ (imported line 12) (reimported)
  • PLW0511 — TODO: (fixme)
  • PLW0611 — Unused import sqlite3 (unused-import)
  • PLW0612 — Unused variable ‘thumbnails’ (unused-variable)
  • PLW0613 — Unused argument ‘range_around_0’ (unused-argument)
  • PLW0614 — Unused import h5py from wildcard import (unused-wildcard-import)
  • PLW0621 — Redefining name ‘seed’ from outer scope (line 12) (redefined-outer-name)
  • PLW0622 — Redefining built-in ‘type’ (redefined-builtin)
  • PLW0631 — Using possibly undefined loop variable ‘deployment’ (undefined-loop-variable)
  • PLW0702 — No exception type(s) specified (bare-except)
  • PLW0703 — Catching too general exception Exception (broad-except)
  • PLW1309 — Using an f-string that does not have any interpolated variables (f-string-without-interpolation)
  • PLW1401 — Anomalous backslash in string: ‘{‘. String constant might be missing an r prefix. (anomalous-backslash-in-string)
  • PLW1514 — Using open without explicitly specifying an encoding (unspecified-encoding)
  • W291 — trailing whitespace
  • W292 — no newline at end of file
  • W293 — blank line contains whitespace
  • W391 — blank line at end of file
  • W503 — line break before binary operator
  • W605 — invalid escape sequence ‘{‘

Понравилась статья? Поделить с друзьями:

Читайте также:

  • E6h ошибка на стиральной electrolux
  • E68 электролюкс ошибка
  • E6501 ошибка микроволновки бош
  • E62 10 sony ошибка
  • E61 ошибка бош

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии