Как исправить ошибку e128 python

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'])



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

Понравилась статья? Поделить с друзьями:
  • Как исправить ошибку dxgkrnl sys
  • Как исправить ошибку dxerror log и directx log
  • Как исправить ошибку dx12 is not supported
  • Как исправить ошибку dx11 required
  • Как исправить ошибку driver error