E122 continuation line missing indentation or outdented как исправить

I get this error but however I choose to indent it, I still get it, do you know why?

if len(argmaxcomp) == 1:
    print "The complex with the greatest mean abundance is: {0}"
    .format(argmaxcomp[0])

asked Oct 15, 2015 at 11:40

user132290's user avatar

1

Generally pep8 suggests you prefer parenthesis over continuation lines.

The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

That is:

if len(argmaxcomp) == 1:
    print("The complex with the greatest mean abundance is: {0}"
          .format(argmaxcomp[0]))

Another option, is to use python 3’s print:

from __future__ import print_function

if len(argmaxcomp) == 1:
    print("The complex with the greatest mean abundance is:", argmaxcomp[0])

Note: print_function may break/require updating the rest of the code… anywhere you’ve used print.

answered Oct 16, 2015 at 17:01

Andy Hayden's user avatar

Andy HaydenAndy Hayden

355k101 gold badges620 silver badges535 bronze badges

The problem in this case is that there is no indentation at all
and obviously the error occurs in the last line.
In case parentheses are not an option just add indentation as below:

if len(argmaxcomp) == 1:
    print "The complex with the greatest mean abundance is: {0}" 
        .format(argmaxcomp[0])

Any amount of spaces works but I don’t know what is preferred.

kon psych's user avatar

kon psych

6161 gold badge11 silver badges26 bronze badges

answered Oct 15, 2015 at 11:51

st0ne's user avatar

st0nest0ne

4,1252 gold badges23 silver badges24 bronze badges

I did’t get the above error, But i have tried below types,
Please post with error, so that we can check

In [6]: argmaxcomp = [100]

In [7]: if len(argmaxcomp) == 1:
   ...:     print 'val: {0}'
   ...:     .format(argmaxcomp[0])
   ...:     
val: 100

In [8]: if len(argmaxcomp) == 1:
   ...:     print 'val: {0}'.format(argmaxcomp[0])
   ...:     
val: 100

In [9]: if len(argmaxcomp) == 1:
   ...:     print 'val: {0}'.format(
   ...:     argmaxcomp[0])
   ...:     
val: 100

answered Oct 15, 2015 at 12:00

Muthuvel's user avatar

MuthuvelMuthuvel

5062 gold badges6 silver badges16 bronze badges

There is one section in the PEP8 that reads:

The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

Backslashes may still be appropriate at times. For example, long, multiple with -statements cannot use implicit continuation, so backslashes are acceptable

This means (even though this has nothing to do with PEP8-E122) that you should wrap it in paranthesis instead of using the backslash and then the implicit line continuation (indentation) is the opening bracket:

if len(argmaxcomp) == 1:
    print("The complex with the greatest mean abundance is: {0}"
          .format(argmaxcomp[0]))
#         ^--------- The bracket opens here

There are only 2 exceptions mentioned where the backslash is acceptable because paranthesis are impossible (because they have another meaning in these contexts):

  • multi-with
  • asserts

However if you really want that backslash (only possible with python2) it should have the same indentation as the first expression:

if len(argmaxcomp) == 1:
    print "The complex with the greatest mean abundance is: {0}" 
          .format(argmaxcomp[0])
#         ^--------- The first expression starts here

Community's user avatar

answered Oct 15, 2015 at 11:49

MSeifert's user avatar

MSeifertMSeifert

144k37 gold badges331 silver badges346 bronze badges

Just had a similar issue and resolved it. I think the problem with the OP’s code is that there may be whitespace between the continuation lines. There should be nothing there but the n.

answered Sep 19, 2017 at 21:13

Malik A. Rumi's user avatar

Malik A. RumiMalik A. Rumi

1,7954 gold badges23 silver badges36 bronze badges

A continuation line is not indented as far as it should be or is indented too far.

Anti-pattern

In this example the second line is missing indentation.

print("Python", (
"Rules"))

Best practice

print("Python", (
    "Rules"))

Additional links

  • https://www.python.org/dev/peps/pep-0008/#indentation

#python #pycharm #refactoring #indentation #pep8

Вопрос:

Когда я получу предупреждение

PEP 8: E122 continuation line missing indentation or outdented

Ctrl Alt L не выполняет необходимые отступы. Вместо этого отступ должен быть сделан вручную.

Как будто этого было недостаточно, если я сделаю Ctrl Alt Lэто позже, строка не будет привязана к предыдущему неверному уровню, что снова вызовет вышеупомянутое предупреждение. Каково решение этой досадной неприятности?

Как и было предложено, вот пример:

 def foo():
    return range(15)


var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, var12, var13, var14, 
var15 = foo()
 

Editor -> Code Style -> Markdown Настройки:

Hard wrap = 80

Wrap on typing = Yes .

Комментарии:

1. Я думаю, что было бы гораздо лучше, если бы вы включили также пример. PyCharm не всегда использует лучшее форматирование (и иногда оно непоследовательно). OTOH PEP8 тоже не без проблем, и иногда просто лучше писать код по-другому

Ответ №1:

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

Показанный код-Python, поэтому соответствующие настройки находятся на File > Settings > Editor > Code Style > Python > Wrapping and Braces .

Если вы посмотрите на скриншот, нужная вам функциональность работает для доступных опций, которые называются Wrap if long (используются вместе с Hard wrap at ограничением). Если вы попытаетесь сделать то же самое для любой из конструкций, у которых есть предыдущая опция (например, импорт), отступ строки продолжения будет автоматически исправлен нажатием Ctrl Alt L. Однако ваш пример предназначен для нескольких объявлений атрибутов в одной строке с распаковкой, для которой нет возможности.

снимок экрана диалога настроек IDE

Это оставляет пользователям 3 распространенных альтернативы:

  1. Используйте Python Black для форматирования кода.
  2. В этом случае выполните форматирование вручную.
  3. Не обращайте внимания на руководство по стилю PEP 8 и отключите предупреждение линтера.

Но, в заключение, это не связано с тем, что вы делаете что-то не так, и где-то нет скрытой настройки, которая позволила бы это сделать. В среде IDE просто нет функции форматирования для этой конкретной конструкции.

Вы также можете отправить запрос на функцию в JetBrains bugtracker.

Generally pep8 suggests you prefer parenthesis over continuation lines.

The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

That is:

if len(argmaxcomp) == 1:
    print("The complex with the greatest mean abundance is: {0}"
          .format(argmaxcomp[0]))

Another option, is to use python 3’s print:

from __future__ import print_function

if len(argmaxcomp) == 1:
    print("The complex with the greatest mean abundance is:", argmaxcomp[0])

Note: print_function may break/require updating the rest of the code… anywhere you’ve used print.

Comments

  • I get this error but however I choose to indent it, I still get it, do you know why?

    if len(argmaxcomp) == 1:
        print "The complex with the greatest mean abundance is: {0}"
        .format(argmaxcomp[0])
    

Recents

У меня есть скрипт на python, и flake8 обнаружил некоторые ошибки для моего скрипта:

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

Вот мой код:

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

Я пробовал разные перестановки, и ни одна из них не работала. Может кто-нибудь сказать мне, как отформатировать эту функцию?

1 ответ

Лучший ответ

E122: Когда вы используете строку продолжения для нескольких аргументов функции, они должны использовать обычный отступ в 4 столбца.

E128: Когда вы распределяете элементы списка, dict, tuple и т. Д. По нескольким строкам, вам нужно выровнять их слева.

t = someFunction (
    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)]
)

Вот документация:

В строке продолжения отсутствует отступ или отступ (E122)

Строка продолжения с отступом для визуального отступа (E128)


0

Barmar
12 Сен 2019 в 23:43

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