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.
Continuation line under-indented for visual indent
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"))
Вопрос:
У меня есть это утверждение как несколько строк:
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"))
Просто открыл файл с помощью Sublime Text (с помощью Sublime Linter) и заметил ошибку форматирования PEP8, которую я никогда раньше не видел. Вот текст:
urlpatterns = patterns('',
url(r'^$', listing, name='investment-listing'),
)
Он помечает второй аргумент, строку, которая начинается url(...)
Я собирался отключить эту проверку в ST2, но я хотел бы знать, что я делаю неправильно, прежде чем я проигнорирую это. Вы никогда не знаете, если это кажется важным, я мог бы даже изменить свои пути
Ответы:
PEP-8 рекомендует использовать отступы для открывающих скобок, если вы помещаете что-либо в первую строку, поэтому он должен иметь отступ для открывающей скобки:
urlpatterns = patterns('',
url(r'^$', listing, name='investment-listing'))
или не ставить какие-либо аргументы в стартовой строке, а затем делать отступы до единого уровня:
urlpatterns = patterns(
'',
url(r'^$', listing, name='investment-listing'),
)
urlpatterns = patterns(
'', url(r'^$', listing, name='investment-listing'))
Я предлагаю прочитать PEP-8 — вы можете пролистать многие из них, и это довольно легко понять, в отличие от некоторых более технических PEP.
Это также относится к таким утверждениям (автоматически отформатированным PyCharm):
return combine_sample_generators(sample_generators['train']),
combine_sample_generators(sample_generators['dev']),
combine_sample_generators(sample_generators['test'])
Который даст такое же стиль-предупреждение. Чтобы избавиться от него, мне пришлось переписать его так:
return
combine_sample_generators(sample_generators['train']),
combine_sample_generators(sample_generators['dev']),
combine_sample_generators(sample_generators['test'])