Pep8 e128 как исправить

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…

pep8 1.3.4 fails to detect an E128 error in a nested function call if subsequent lines are outdented to match the function call.

Tested with the following example file:


def correct():
    return a_really_really_long_function_call(the_first_parameter,
                                              another_function_call(
                                                  'string',
                                                  other_func_param=param_val),
                                              param3=third_func(some_arg))


def fails_e128():
    return a_really_really_long_function_call(the_first_parameter,
                                              another_function_call('string',
                                                  other_func_param=param_val),
                                              param3=third_func(some_arg))


def should_fail():
    # Actually passes
    return a_really_really_long_function_call(the_first_parameter,
                                              another_function_call('string',
                                              other_func_param=param_val),
                                              param3=third_func(some_arg))

Output:

$ pep8 --version
1.3.4
$ pep8 pep8_test.py 
pep8_test.py:14:51: E128 continuation line under-indented for visual indent

У меня есть это утверждение в несколько строк:

    return render_to_response('foo/page.html',
        {
            'situations': situations,
            'active': active_req,
        },
        context_instance=RequestContext(request))

В настоящее время, используя скрипт PEP8, он выдает ошибку «E128: строка продолжения с отступом для визуального отступа» во второй строке.

Я перепробовал целый ряд разных способов форматирования, и единственный способ заставить PEP8 перестать жаловаться:

    return render_to_response('foo/page.html', {
        'situations': situations,
        'active': active_req,
    },
        context_instance=RequestContext(request))

Но это похоже на мусор.

Предложения ? Е124, Е126 и Е128 кажутся огромной болью!

Я не против решений, которые имеют { в первой строке (или сами по себе), но я надеюсь, что есть решение, где }, и context_instance... находятся на одном уровне отступа ,

3 ответа

Лучший ответ

Проблема в том, что все параметры должны иметь отступ на одном уровне. Это включает в себя любые параметры в начальной строке вызова функции.

Итак, пока вы могли исправить это так:

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)


22

abarnert
28 Авг 2013 в 20:58

Вы когда-нибудь пробовали использовать django-раздражающий?

Ты можешь сделать это…

@render_to('foo/page.html')
def bar(request):
    return {'situations': situations,
            'active': active_req,}

Я думаю, что это чище, и это может помочь вам в стиле PEP8 …


4

MemoGarcia
28 Авг 2013 в 20:57

Я почти уверен, что он хочет, чтобы вы делали отступ перед открывающими скобками (если вам нужен параметр там) — т.е.

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 о правильной практике отступов.

Вот соответствующие примеры из спецификации для проходящего мимо странника:

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)


4

vroomfondel
28 Авг 2013 в 21:05

Проблема заключается в том, что все параметры должны быть отступом до одного уровня. Это включает в себя любой параметр в строке вызова начальной функции.

Итак, хотя вы можете исправить это следующим образом:

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)

Понравилась статья? Поделить с друзьями:
  • Память народа как найти участника вов
  • Как найти тематические слова
  • Как найти рентабельность активов roa
  • Как можно найти елочку
  • Как найти время полета вверх