For lines that are too long (e.g. > 79 characters), you can use parentheses to group your conditions:
if (first_index < 0
or second_index > self._number_of_plates - 1
or condition2
and candition3):
raise ValueError
Note that any boolean conditions (or
, and
) should go at the start of the line before the condition.
In your case, there is a special rule because of the if (...)
construct:
When the conditional part of an if-statement is long enough to require
that it be written across multiple lines, it’s worth noting that the
combination of a two character keyword (i.e. if), plus a single space,
plus an opening parenthesis creates a natural 4-space indent for the
subsequent lines of the multiline conditional. This can produce a
visual conflict with the indented suite of code nested inside the
if-statement, which would also naturally be indented to 4 spaces. This
PEP takes no explicit position on how (or whether) to further visually
distinguish such conditional lines from the nested suite inside the
if-statement. Acceptable options in this situation include, but are
not limited to:
# No extra indentation.
if (this_is_one_thing and
that_is_another_thing):
do_something()
# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()
# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
do_something()
(Also see the discussion of whether to break before or after binary
operators below.)
Source: PEP 8 Style Guide
A continuation line is indented farther than it should be for a visual indent.
Anti-pattern
In this example, the string "World"
is indented two spaces farther than it should be.
print("Python", ("Hello",
"World"))
Best practice
print("Python", ("Hello",
"World"))
Additional links
- https://www.python.org/dev/peps/pep-0008/#indentation
elpy
(or rather flake8
I suppose) complains about a line over-indented on the line 52 (see below image)
I tried to change this line’s begin but no change.
I always use TAB to have the correct indentation (and this position is where TAB leads).
Here’s my elpy
config:
Emacs.............: 26.3
Elpy..............: 1.33.0
Virtualenv........: None
Interactive Python: python3 3.8.3 (/usr/bin/python3)
RPC virtualenv....: rpc-venv (/home/david/.emacs.d/elpy/rpc-venv)
Python...........: /usr/bin/python3 3.8.3 (/usr/bin/python3)
Jedi.............: 0.17.0
Rope.............: 0.17.0
Autopep8.........: 1.5.2
Yapf.............: 0.30.0
Black............: 19.10b0
Syntax checker....: flake8 (/home/david/.local/bin/flake8)
asked May 22, 2020 at 13:49
You should create in your home folder a .flake8rc
file, and add some content to ignore that error – documented here and below is a small template:
[flake8]
# it's not a bug that we aren't using all of hacking
ignore =
# F812: list comprehension redefines ...
F812,
# H101: Use TODO(NAME)
H101,
# H202: assertRaises Exception too broad
H202,
# E127: continuation line over-indented for visual indent
E127
The full error code listing is here
answered May 24, 2020 at 6:53
IanIan
1,29610 silver badges12 bronze badges
1
Вопрос:
У меня есть эта строка кода, которая проходит по линии и при тестировании ошибок pep8 я получаю:
линия слишком длинная. Поэтому, чтобы попытаться исправить это, я использовал слэш (‘’), но затем я получаю строку продолжения с отступом для визуального отступа. Что я могу сделать, чтобы исправить это?
Вещи, которые я пробовал:
if first_index < 0 or second_index >
self._number_of_plates - 1:
raise ValueError
continuation line over-indented for visual indent
if first_index < 0
or second_index >
self._number_of_plates - 1:
raise ValueError
continuation line over-indented for visual indent
if first_index < 0 or
second_index > self._number_of_plates - 1:
raise ValueError
continuation line over-indented for visual indent
if first_index
< 0 or second_index
> self._number_of_plates - 1:
raise ValueError
continuation line over-indented for visual indent
Лучший ответ:
У линии с обратной косой чертой возникает проблема с завершающим пробелом, который может нарушить ваш код. Это популярное исправление и совместимо с PEP8:
if (first_index < 0 or
second_index > self._number_of_plates - 1):
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
Open
anntzer opened this issue
Sep 10, 2017
· 5 comments
· May be fixed by #866
Comments
Consider
[obj for obj in iterator
if some_long_cond()
and some_other_cond()]
(obj for obj in iterator
if some_long_cond()
and some_other_cond())
sorted(obj for obj in iterator
if some_long_cond()
and some_other_cond())
I would consider that this is a reasonable, and perhaps even the correct way to indent such expressions, assuming you adhere to the “binary operators after linebreak” school and also assuming that the expressions are too long to fit in a single line.
Interestingly, pycodestyle is happy with the indenting of the first two expressions, but complains about the last one
test.py:9:11: E127 continuation line over-indented for visual indent
(Note that it is able to recognize the correct amount of indenting needed in the first two expressions — adding or removing a space before “and” results in the same warning as for the third expression.)
Edit: note to self or whoever will work on this: the first two cases actually work “accidentally” because the indent of the last line is 4 characters, which is always accepted — prepending the thing e.g. with the_list = [...
and indenting the rest to align makes the thing fail again.)
I think the fundamental construct here is the conditional. The proposed indentation doesn’t work outside of comprehensions either:
abc = (1 if a
and 2
else b)
I don’t think PEP 8 mentions anything about this, but I haven’t looked either.
Copy link
Contributor
Author
The conditional in
(foo for foo in bar if quux)
and in
(foo if bar else quux)
are quite different objects (one is a clause to a comprehension, the other a ternary).
That is correct. I was just thinking that inline if
wasn’t considered for indentation rules at all and pointing to another usage of it.
anntzer
linked a pull request
May 13, 2019
that will
close
this issue
I’m getting a related problem with the following code:
import pandas as pd data = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [0, 0, 0, 0, 0], 'C': [4, 5, 6, 7, 8]}) nonzero = (data != 0) print(nonzero)
I get E128 continuation line underindented on the print(col) line. Looks like the parenthesis around data != 0
is confusing it somehow.
@flutefreak7 I cannot reproduce, please create a new issue with more information (version, etc.)
asottile
changed the title
“continuation line over-indented” when comprehension is an argument
E127: “continuation line over-indented” when comprehension is an argument
Jun 14, 2020