E128 continuation line under indented for visual indent как исправить

This case is covered in PEP-8. In summary, to fix this you need to ensure that when you indent lines that are inside parentheses that you align the next line with the character that is after the opening parenthesis. For example, you should do this when you continue code in parentheses.

foo(a, b, c, 
    d, e)

You are currently doing it like this.

foo(a, b, c, 
  d, e)

To fix your indentation you should do it like this.

command = 'ffmpeg -i downloaded.mp4 -codec:v libx264 -codec:a 
           aac -map 0 -f ssegment -segment_format mpegts 
           -segment_list %s/%skbps.m3u8 -segment_time 10 
           %s/%skbps_%%03d.ts' % (path, options['video_bitrate'],
                                  path, options['video_bitrate'])

From Stephen Rauch’s answer you may have noticed that there is a little more to this as well. instead of using slashes to do line continuation you may surround the entire line in parenthesis and then break the lines into strings, python automatically joins adjacent string literals. For example if you had a string and you did this before.

greeting = 'Hello, 
            World!'

You should do this instead.

greet = ('Hello, '
         'World!')

This way is a lot more readable and a lot nicer for you to work with. Also do note, there is another PEP-8 approved way to continue parenthesis lines. Instead of doing.

foo(a, b, c, 
    d, e)

You may also do this.

foo(
    a, b, c, 
    d, e)

To do this you must leave the first line blank after the opening parentheses and then you MUST indent in from the current block to start your continuation. I hope this edit furthers your understanding more. If you want to learn more about python style, then just give the PEP guides a quick read through (they are the standard for python code).

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…

@Dreamsorcerer

It could be more helpful for a developer new to a codebase, that perhaps doesn’t know the indentation still in use, to be told exactly where the indentation should go.

This could just be added to the end of the error like (expected 20, got 8).

@sigmavirus24

Your description isn’t comprehensible to me. Can you add an example of what you’re running against, what you’re getting and how what you’re proposing helps?

@asottile

I believe what the original post is asking for is something like this (really ugly example, but):

if True:
    if (a() and
    b()):
        print('hi')
$ ~/opt/venv/bin/pycodestyle t.py
t.py:3:5: E128 continuation line under-indented for visual indent

but OP would like to see

$ ~/opt/venv/bin/pycodestyle t.py
t.py:3:5: E128 continuation line under-indented for visual indent (indented 4 spaces, expected 8 or 12 spaces)

but I guess that demonstrates another problem, there’s multiple things that could be suggested for each code. satisfying one of them may also break another code (for example, 8 spaces is ok for E128 but then triggers E129)

@Dreamsorcerer

Indeed. I got the idea from flake8-tabs, which I noticed adds this information (but, unless you want to use tabs, it does nothing else of interest).

@sigmavirus24

I guess that demonstrates another problem, there’s multiple things that could be suggested for each code

Yes, well I think baby steps towards the right solution is a fair thing to do. Adding «indented 4 spaces but expected 8 or 12 spaces» could be helpful to even someone just new to this tool, let alone a random codebase. As we aggregate the most common pain-points of these hints we can make the hints slightly better to reduce annoyance.

@asottile
asottile

changed the title
Indentation checks (e.g. E128) could contain exact information

E128: Indentation checks could contain exact information

Jun 14, 2020


Просто открыл файл с помощью 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'])



Понравилась статья? Поделить с друзьями:
  • Как найти файл в telnet
  • Как найти сертификаты на компьютере windows 10
  • Как составить проект публичного выступления
  • Как найти где лежат балки
  • Как найти перемещение точки физика