New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Closed
methane opened this issue
Feb 17, 2013
· 17 comments
Closed
E126 hanging indent is too strict
#167
methane opened this issue
Feb 17, 2013
· 17 comments
Comments
from os import( path, listdir)
This cause “E126 continuation line over-indented for hanging indent”.
But below code is OK. from ... import (
should be handled like that.
# More indentation included to distinguish this from the rest. def long_function_name( var_one, var_two, var_three, var_four): print(var_one)
Thank you for your feedback.
AFAICT, the first example does not trigger any warning with the pep8
tool.
For the second example, this was a deliberate choice of the E12
checks on issue #64 (@samv proposal). The PEP-8 itself advocates for “Use 4 spaces per indentation level.” without excluding continuation lines indentation from this rule.
The spirit of the E12 check is to enforce PEP-8 for continuation lines, and to avoid inconsistent indentations through the code.
Of course each check can be ignored with --ignore E12
for example.
Copy link
Contributor
Author
I’m sorry about wrong first example.
What I want to say is:
from os import( path, listdir, )
This cause “E126 continuation line over-indented for hanging indent” and
“E123 closing bracket does not match indentation of opening bracket’s line”.
@methane an alternate way of writing that is:
from os import (path, foo, bar, bogus, #etc listdir, unlink, #etc, )
@methane, you have one too many indents.
from os import (
path,
listdir,
)
Copy link
Contributor
Author
@myint That rule isn’t applied to hanging indent.
Well, the PEP 8 recommends “Use 4 spaces per indentation level.”
And there’s no objective reason to apply a different rule for continuation line indentation.
The purpose of these E12* rules is to conform to PEP 8 and enforce some consistency for the indentation.
Copy link
Contributor
Author
“per level” means indent for block.
It’s not for continuation line.
“per level” means indent for block.
It’s not for continuation line.
This is your interpretation of PEP 8.
If you want to be creative about your indentation, you can disable the E12 checks in the configuration.
Copy link
Contributor
Author
This is your interpretation of PEP 8.
pep8 says:
there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.
…
Optional:# Extra indentation is not necessary. foo = long_function_name( var_one, var_two, var_three, var_four)http://www.python.org/dev/peps/pep-0008/#indentation
I believe no one can interpret this to “hanging indent should be 1-level 4-space indent.”
If you want to be creative about your indentation, you can disable the E12 checks in the configuration.
Yes, I already disabled it. But I think too strict default hurts new users.
I have a similar “too strict” issue with E126.
cmd = 'git archive{prefix}{fmt} -o {output} {rev}'.format(
rev = rev,
output = output,
fmt = ' --format={0}'.format(fmt) if fmt else '',
prefix = ' --prefix="{0}"'.format(prefix if prefix else basename)
)
triggers E126, but I think this should be allowed to distinguish from an actual new indent level. Pulling the last ) onto the line above makes no difference.
@basepi, --ignore=E126
. (The whole point of E126 is to complain about indentation greater than 4 spaces.)
@myint Heh, thanks for this. I was just wondering if we wanted to try to bring it in line with PEP8. =)
I think 4 is the most used convention in the Python code base. The following will show lines that end with (
and the line that immediately follows it.
locate .py | grep '.py$' | grep python3.3 | xargs grep -A1 '($'
So in terms of following a convention, I think E126 is the way to go. If one prefers 8 instead 4, then I think --ignore=E126
is probably the best option.
Cool! Thanks for the quick reply.
Copy link
Contributor
Author
@myint Thank you. I agree E126 is not too strict for now.
@methane said
I believe no one can interpret this to “hanging indent should be 1-level 4-space indent.”
The 4aec4d180429 revision of PEP-8, updated 2014-05-20, explicitly aligns with @methane’s assertion:
The 4-space rule is optional for continuation lines.
Optional:
# Hanging indents *may* be indented to other than 4 spaces. foo = long_function_name( var_one, var_two, var_three, var_four)
pep8 needs to revise its hanging indent rules. The number of spaces within a hanging indent needs only to be consistent; 2 spaces, 4 spaces, 8 spaces – all are valid amounts of space for hanging indents.
@gotgenes I disagree that pep8 needs a fix because in the Yes
section (which you helpfully omitted) it says:
# Hanging indents should add a level.
foo = long_function_name(
var_one, var_two,
var_three, var_four)
And the example level it uses is 4 spaces. In other words, pep8 is still correct, and the ability to turn off this check keeps with the PEP’s understanding of optional
.
Try downloading code style linters such as pep8 (a program which checks your code to see if it matches PEP 8 requirements) or pylint. You can find a more comprehensive list and comparison of Python style checkers here: What are the comprehensive lint checkers for Python?
In fact, there’s a pep8 checker available online: http://pep8online.com/
If we run your code through that, it tells you:
Code Line Column Text
E126 2 29 continuation line over-indented for hanging indent
E225 2 70 missing whitespace around operator
E126 4 45 continuation line over-indented for hanging indent
E501 4 80 line too long (90 > 79 characters)
W292 7 30 no newline at end of file
The fixed version of your code would look more like this:
result = urllib.urlretrieve(
"https://secure.gravatar.com/avatar.php?" +
urllib.urlencode({
'gravatar_id': hashlib.md5(email).hexdigest(),
'size': srt(size)
})
)
In essence, the main PEP 8 violation you had was that you were indenting too much. A single indent is fine — you don’t need to align to the opening paren of the function calls. Python is also insistent that your lines don’t go beyond 80 characters, but fixing the over-indentation also fixed that issue.
It is possible to select and ignore certain violations reported by Flake8
and the plugins we’ve installed. It’s also possible as of Flake8 3.0 to
combine usage of flake8 --select
and flake8 --ignore
. This
chapter of the User Guide aims to educate about how Flake8 will report errors
based on different inputs.
Ignoring Violations with Flake8¶
By default, Flake8 has a list of error codes that it ignores. The list used
by a version of Flake8 may be different than the list used by a different
version. To see the default list, flake8 --help
will
show the output with the current default list.
Extending the Default Ignore List¶
If we want to extend the default list of ignored error codes, we can use
flake8 --extend-ignore
to specify a comma-separated list of codes
for a specific run on the command line, e.g.,
flake8 --extend-ignore=E1,E23 path/to/files/ path/to/more/files
This tells Flake8 to ignore any error codes starting with E1
and E23
,
in addition the default ignore list. To view the default error code ignore
list, run flake8 --help
and refer to the help text for
flake8 --ignore
.
Overriding the Default Ignore List¶
If we want to completely override the default list of ignored error codes, we
can use flake8 --ignore
to specify a comma-separated list of codes
for a specific run on the command-line, e.g.,
flake8 --ignore=E1,E23,W503 path/to/files/ path/to/more/files/
This tells Flake8 to only ignore error codes starting with E1
, E23
,
or W503
while it is running.
Note
The documentation for flake8 --ignore
shows examples for how
to change the ignore list in the configuration file. See also
Configuring Flake8 as well for details about how to use configuration
files.
In-line Ignoring Errors¶
In some cases, we might not want to ignore an error code (or class of error
codes) for the entirety of our project. Instead, we might want to ignore the
specific error code on a specific line. Let’s take for example a line like
example = lambda: 'example'
Sometimes we genuinely need something this simple. We could instead define
a function like we normally would. Note, in some contexts this distracts from
what is actually happening. In those cases, we can also do:
example = lambda: 'example' # noqa: E731
This will only ignore the error from pycodestyle that checks for lambda
assignments and generates an E731
. If there are other errors on the line
then those will be reported. # noqa
is case-insensitive, without the colon
the part after # noqa
would be ignored.
Note
If we ever want to disable Flake8 respecting # noqa
comments, we can
refer to flake8 --disable-noqa
.
If we instead had more than one error that we wished to ignore, we could
list all of the errors with commas separating them:
Finally, if we have a particularly bad line of code, we can ignore every error
using simply # noqa
with nothing after it.
Contents before and after the # noqa: ...
portion are ignored so multiple
comments may appear on one line. Here are several examples:
# mypy requires `# type: ignore` to appear first x = 5 # type: ignore # noqa: ABC123 # can use to add useful user information to a noqa comment y = 6 # noqa: ABC456 # TODO: will fix this later
Ignoring Entire Files¶
Imagine a situation where we are adding Flake8 to a codebase. Let’s further
imagine that with the exception of a few particularly bad files, we can add
Flake8 easily and move on with our lives. There are two ways to ignore the
file:
-
By explicitly adding it to our list of excluded paths (see:
flake8
)
--exclude -
By adding
# flake8: noqa
to the file
The former is the recommended way of ignoring entire files. By using our
exclude list, we can include it in our configuration file and have one central
place to find what files aren’t included in Flake8 checks. The latter has the
benefit that when we run Flake8 with flake8 --disable-noqa
all of
the errors in that file will show up without having to modify our
configuration. Both exist so we can choose which is better for us.
Selecting Violations with Flake8¶
Flake8 has a default list of violation classes that we use. This list is:
-
C90
All
C90
class violations are reported when the user specifies
flake8 --max-complexity
-
E
All
E
class violations are “errors” reported by pycodestyle -
F
All
F
class violations are reported by pyflakes -
W
All
W
class violations are “warnings” reported by pycodestyle
This list can be overridden by specifying flake8 --select
. Just as
specifying flake8 --ignore
will change the behaviour of Flake8, so
will flake8 --select
.
Let’s look through some examples using this sample code:
# example.py def foo(): print( "Hello" "World" )
By default, if we run flake8
on this file we’ll get:
example.py:4:9: E131 continuation line unaligned for hanging indent
Now let’s select all E
class violations:
flake8 --select E example.py
example.py:3:17: E126 continuation line over-indented for hanging indent example.py:4:9: E131 continuation line unaligned for hanging indent example.py:5:9: E121 continuation line under-indented for hanging indent
Suddenly we now have far more errors that are reported to us. Using
--select
alone will override the default --ignore
list. In these cases,
the user is telling us that they want all E
violations and so we ignore
our list of violations that we ignore by default.
We can also be highly specific. For example, we can do
flake8 --select E121 example.py
example.py:5:9: E121 continuation line under-indented for hanging indent
We can also specify lists of items to select both on the command-line and in
our configuration files.
flake8 --select E121,E131 example.py
example.py:4:9: E131 continuation line unaligned for hanging indent example.py:5:9: E121 continuation line under-indented for hanging indent
Selecting and Ignoring Simultaneously For Fun and Profit¶
Prior to Flake8 3.0, all handling of flake8 --select
and
flake8 --ignore
was delegated to pycodestyle. Its handling of the
options significantly differs from how Flake8 3.0 has been designed.
pycodestyle has always preferred --ignore
over --select
and will
ignore --select
if the user provides both. Flake8 3.0 will now do its
best to intuitively combine both options provided by the user. Let’s look at
some examples using:
# example.py import os def foo(): var = 1 print( "Hello" "World" )
If we run Flake8 with its default settings we get:
example.py:1:1: F401 'os' imported but unused example.py:5:5: F841 local variable 'var' is assigned to but never used example.py:8:9: E131 continuation line unaligned for hanging indent
Now let’s select all E
and F
violations including those in the default
ignore list.
flake8 --select E,F example.py
example.py:1:1: F401 'os' imported but unused example.py:5:5: F841 local variable 'var' is assigned to but never used example.py:7:17: E126 continuation line over-indented for hanging indent example.py:8:9: E131 continuation line unaligned for hanging indent example.py:9:9: E121 continuation line under-indented for hanging indent
Now let’s selectively ignore some of these while selecting the rest:
flake8 --select E,F --ignore F401,E121 example.py
example.py:5:5: F841 local variable 'var' is assigned to but never used example.py:7:17: E126 continuation line over-indented for hanging indent example.py:8:9: E131 continuation line unaligned for hanging indent
Via this example, we can see that the most specific user-specified rule
will win. So in the above, we had very vague select rules and two very
specific ignore rules. Let’s look at a different example:
flake8 --select F401,E131 --ignore E,F example.py
example.py:1:1: F401 'os' imported but unused example.py:8:9: E131 continuation line unaligned for hanging indent
In this case, we see that since our selected violation codes were more
specific those were reported.
#21288
closed
Cleanup/optimization
(fixed)
Reported by: | Owned by: | nobody | |
---|---|---|---|
Component: | Core (Other) | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Accepted | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | yes | UI/UX: | no |
To find errors, ensure you have an up-to-date master with the flake8 config in setup.cfg, then remove E126 from the ignore list there. You can then run flake8
from the directory with setup.cfg in it to list all errors – there should be about 300.
Attaching an example patch to get you started.
Apply it, if you’d like:
patch -p1 -i E126.diff
Attachments (2)
Change History (6)
Resolution: | → fixed |
---|---|
Status: |
new → closed |
Note: See
TracTickets for help on using
tickets.
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.error
It 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 tabs
For 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 |