I have this statement as a few lines:
return render_to_response('foo/page.html',
{
'situations': situations,
'active': active_req,
},
context_instance=RequestContext(request))
As it stands, using the PEP8 script, it gives me an «E128: continuation line under-indented for visual indent» error on the second line.
I’ve tried a whole bunch of different ways of formatting, and the only way I can get PEP8 to stop complaining is:
return render_to_response('foo/page.html', {
'situations': situations,
'active': active_req,
},
context_instance=RequestContext(request))
But this looks like garbage.
Suggestions? E124, E126, and E128 seem to be a huge pain!
I don’t mind solutions which have the { on the first line (or on it’s own), but I hope there’s a solution where the }, and context_instance... are at the same indentation level.
Вопрос:
У меня есть это утверждение как несколько строк:
return render_to_response('foo/page.html',
{
'situations': situations,
'active': active_req,
},
context_instance=RequestContext(request))
Как и в случае с PEP8 script, он дает мне ошибку “E128: продолжение линии с отступом для визуального отступа” во второй строке.
Я пробовал целую кучу разных способов форматирования, и единственный способ заставить PEP8 перестать жаловаться:
return render_to_response('foo/page.html', {
'situations': situations,
'active': active_req,
},
context_instance=RequestContext(request))
Но это похоже на мусор.
Предложения? E124, E126 и E128 кажутся огромной болью!
Я не против решений, которые имеют { в первой строке (или на ней), но я надеюсь, что там есть решение, где }, и context_instance... находятся на одинаковом уровне отступов.
Лучший ответ:
Проблема заключается в том, что все параметры должны быть отступом до одного уровня. Это включает в себя любой параметр в строке вызова начальной функции.
Итак, хотя вы можете исправить это следующим образом:
return render_to_response('foo/page.html',
{
'situations': situations,
'active': active_req,
},
context_instance=RequestContext(request))
…, который обычно просто заставит вас справиться с правилом 80 столбцов и, безусловно, сделает ваш код более уродливым, даже если pep8 не будет жаловаться. Что вы, вероятно, хотите, так это:
return render_to_response(
'foo/page.html',
{
'situations': situations,
'active': active_req,
},
context_instance=RequestContext(request))
Или, конечно, вы могли бы просто разбить свое гигантское выражение:
d = {
'situations': situations,
'active': active_req,
}
context = RequestContext(request)
return render_to_response('foo/page.html', d, context_instance=context)
Ответ №1
Я уверен, что он хочет, чтобы вы отступали все от начальных парнеров (если вам нужен параметр там) – т.е.
return render_to_response('foo/page.html',
{
'situations': situations,
'active': active_req,
},
context_instance=RequestContext(request))
в противном случае,
return render_to_response(
'foo/page.html',
{
'situations': situations,
'active': active_req,
},
context_instance=RequestContext(request))
также должен быть законным.
Или некоторые такие. См. pep docs о правильных методах отступов
Вот соответствующие примеры из спецификации для проходящего странника:
Yes: # Aligned with opening delimiter foo = long_function_name(var_one, var_two, var_three, var_four) # More indentation included to distinguish this from the rest. def long_function_name( var_one, var_two, var_three, var_four): print(var_one) No: # Arguments on first line forbidden when not using vertical alignment foo = long_function_name(var_one, var_two, var_three, var_four) # Further indentation required as indentation is not distinguishable def long_function_name( var_one, var_two, var_three, var_four): print(var_one) Optional: # Extra indentation is not necessary. foo = long_function_name( var_one, var_two, var_three, var_four)
Ответ №2
Вы когда-нибудь пробовали django-annoying?
вы можете сделать это…
@render_to('foo/page.html')
def bar(request):
return {'situations': situations,
'active': active_req,}
Я думаю, что это чище, и это может помочь вам с стилем PEP8…
I have a python script and flake8 detected some errors for my script:
231 flake8
E128 continuation line under-indented for visual indent
232 flake8
E128 continuation line under-indented for visual indent
234 flake8
E128 continuation line under-indented for visual indent
235 flake8
E122 continuation line missing indentation or outdented
236 flake8
E122 continuation line missing indentation or outdented
Here is my code:
t = someFunction (
data, title=so, Rows=1,
Widths=[1.2 * inch, 0.3 * inch,
0.1 * inch, 0.3 * inch, 2 * inch, 3 * inch,
5.00 * inch],
style=[("sth1", (0, 0), (-1, -1), "CENTER"),
("sth2", (0, 0), (-1, -1), "CENTER"),
('sth3', (0, 0), (-1, -1), 0.5, colors.grey),
('sth4', (0, 0), (-1, 0), colors.orange),
('sth5', (0, 1), (0, -1), colors.orange),
])
I tried different permutations, and none work. Could anyone tell me how to format this function?
Permalink
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
-
Go to file
-
Copy path
-
Copy permalink
Cannot retrieve contributors at this time
| code | message | title | links |
|---|---|---|---|
|
E128 |
Continuation line under-indented for visual indent |
Continuation line under-indented for visual indent (E128) |
https://www.python.org/dev/peps/pep-0008/#indentation |
A continuation line is under-indented for a visual indentation.
Anti-pattern
In this example the string "World" is under-indented by two spaces.
print("Python", ("Hello", "World"))
Best practice
print("Python", ("Hello", "World"))
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 |
