E251 python ошибка

I'm a Python beginner, I read pep standards which must follow while programming in python http://legacy.python.org/dev/peps/pep-0008 Now I have a doubt. As they have mentioned that you should not...

I’m a Python beginner, I read pep standards which must follow while programming in python
http://legacy.python.org/dev/peps/pep-0008

Now I have a doubt. As they have mentioned that you should not put spaces around the equal sign while using keyword argument or a default parameter value in functions or Dict.

For example

YES

def myfunc(key1=val1, key2=val2, key3=val3)

NO

def myfunc(key1 = val1, key2 = val2, key3 = val3)

Thats fine but what if I break down these in multiple lines. something like this(when we have many parameters or long name)

def myfunc(key1=val1,
key2=val2,
key3=val3)

In this case, I think, we should put space around the equal sign. am I correct. because these all are about readability but I’m just curious if there is standard for this too. Looking for best practices.

Same thing for Dict.

new_dict= Dict(
       key1=val1, 
       key2=val2, 
       key3=val3
)

And should I put a comma after last argument in dict unlike example mentioned above, I didn’t put a comma after last value (key3=val3)

asked Jul 17, 2014 at 18:18

user3810188's user avatar

user3810188user3810188

3011 gold badge3 silver badges14 bronze badges

1

Thats fine but what if I break down these in multiple lines. something like this(when we have many parameters or long name)

def myfunc(key1=val1, 
       key2=val2, 
       key3=val3)

In the code you give, you are not putting whitespace around the =, so you are complying with pep8 in respect of operator spacing (your indentation does not comply with pep8).

In general, you can write your code however you like. If you don’t comply with pep8, other people generally won’t find your code as easy to read. If you have local standards within your company, that should supercede pep8. If you don’t have standards that direct you to violate pep8, your colleagues will likely hate you for breaking pep8.

If you don’t have a standard at all, future you will also hate present you.

answered Jul 17, 2014 at 18:23

Marcin's user avatar

MarcinMarcin

47.9k17 gold badges127 silver badges199 bronze badges

PEP8 clearly says:

Don’t use spaces around the = sign when used to indicate a keyword
argument or a default parameter value.

You don’t need to put white spaces around the equal sign in both cases.

If you are not sure whether your code follows PEP8 standard or not, use flake8 static code analysis tool. It would raise warnings in case of code style violations.

Example:

Consider you have extra whitespaces around the equal signs:

def myfunc(key1 = 'val1',
           key2 = 'val2',
           key3 = 'val3'):
    return key1, key2, key3

flake8 outputs a warning for every unexpected whitespace:

$ flake8 test.py
test.py:3:16: E251 unexpected spaces around keyword / parameter equals
test.py:3:18: E251 unexpected spaces around keyword / parameter equals
test.py:4:16: E251 unexpected spaces around keyword / parameter equals
test.py:4:18: E251 unexpected spaces around keyword / parameter equals
test.py:5:16: E251 unexpected spaces around keyword / parameter equals
test.py:5:18: E251 unexpected spaces around keyword / parameter equals

answered Jul 17, 2014 at 18:26

alecxe's user avatar

alecxealecxe

455k116 gold badges1061 silver badges1180 bronze badges

7

No. Don’t put spaces around equal signs when declaring kwargs. Think of it this way: If you are just skimming lines of code, you want to train your eyes to see the difference between the assignment operator used during ordinary program flow (spam = True) and a kwarg, especially if it’s on its own line (spam=True).

As for a trailing comma, I have always felt that a trailing comma suggests to a fellow team member or reader that I feel the list, dict, set of args, etc. might be subject to expansion in the future. If I’m fairly certain that the structure represents its mature state, I remove it.

answered Jul 17, 2014 at 18:23

jMyles's user avatar

jMylesjMyles

11.6k6 gold badges42 silver badges56 bronze badges

1

Я начинающий Python, я читаю стандарты pep, которые должны следовать при программировании на python. Http://legacy.python.org/dev/peps/pep-0008

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

Например

ДА

def myfunc(key1=val1, key2=val2, key3=val3)

НЕТ

def myfunc(key1 = val1, key2 = val2, key3 = val3)

Thats штраф, но что, если я сломаю их в несколько строк. что-то вроде этого (когда у нас много параметров или длинное имя)

def myfunc(key1=val1, key2=val2, key3=val3)

В этом случае, я думаю, мы должны положить пространство вокруг знака равенства. я прав. потому что все это о читаемости, но мне просто любопытно, есть ли для этого стандарт. Ищите лучшие практики.

То же самое для Дикта.

new_dict= Dict(
       key1=val1, 
       key2=val2, 
       key3=val3
)

И я должен поместить запятую после последнего аргумента в dict в отличие от упомянутого выше примера, я не поместил запятую после последнего значения (key3 = val3)

17 июль 2014, в 20:41

Поделиться

Источник

3 ответа

PEP8 четко говорит:

Не используйте пробелы вокруг знака = при использовании для указания аргумента ключевого слова или значения параметра по умолчанию.

В обоих случаях вам не нужно помещать пробелы вокруг знака равенства.

Если вы не уверены, соответствует ли ваш код стандарту PEP8 или нет, используйте инструмент анализа статического кода flake8. Это приведет к предупреждению в случае нарушения стиля кода.

Пример:

У вас есть дополнительные пробелы вокруг равных знаков:

def myfunc(key1 = 'val1',
           key2 = 'val2',
           key3 = 'val3'):
    return key1, key2, key3

flake8 выводит предупреждение для каждого неожиданного пробела:

$ flake8 test.py
test.py:3:16: E251 unexpected spaces around keyword / parameter equals
test.py:3:18: E251 unexpected spaces around keyword / parameter equals
test.py:4:16: E251 unexpected spaces around keyword / parameter equals
test.py:4:18: E251 unexpected spaces around keyword / parameter equals
test.py:5:16: E251 unexpected spaces around keyword / parameter equals
test.py:5:18: E251 unexpected spaces around keyword / parameter equals

alecxe
17 июль 2014, в 16:21

Поделиться

Thats штраф, но что, если я сломаю их в несколько строк. что-то вроде этого (когда у нас много параметров или длинное имя)

def myfunc(key1=val1, 
       key2=val2, 
       key3=val3)

В коде, который вы указываете, вы не помещаете пробелы вокруг =, так что вы соблюдаете pep8 в отношении расстояния между операторами (ваш отступ не соответствует pep8).

В общем, вы можете написать свой код, как вам нравится. Если вы не согласны с pep8, другие люди обычно не смогут найти ваш код как легко читаемый. Если у вас есть локальные стандарты в вашей компании, это должно быть отменено pep8. Если у вас нет стандартов, которые заставляют вас нарушать pep8, ваши коллеги, скорее всего, ненавидят вас за нарушение pep8.

Если у вас нет стандарта вообще, в будущем вы также будете ненавидеть подарок.

Marcin
17 июль 2014, в 16:36

Поделиться

Нет. Не помещайте пробелы вокруг равных знаков при объявлении kwargs. Подумайте об этом так: если вы просто просматриваете строки кода, вы хотите тренировать свои глаза, чтобы увидеть разницу между оператором присваивания, используемым во время обычного потока программы (спам = True) и kwarg, особенно если он на собственной линии (спам = True).

Что касается конечной запятой, я всегда чувствовал, что конечная запятая предлагает коллеге или читателю, что я чувствую, что список, dict, множество аргументов и т.д. Могут быть подвержены расширению в будущем. Если я достаточно уверен, что структура представляет его зрелое состояние, я удаляю его.

jMyles
17 июль 2014, в 15:41

Поделиться

Ещё вопросы

  • 0Разделить QString на — (тире) символ, доступ к элементу списка
  • 0IE8: странная граница вокруг HTML-элемента кнопки
  • 1Невозможно загрузить библиотеку native-hadoop для вашей платформы … с использованием встроенных классов java, где это применимо
  • 0Включение еще одного объединения в таблицу MYSQL
  • 1Группировка результатов Solr в Solr 3.6.1 API вызывает исключение NullPointerException при разборе результата
  • 0клиент c ++ с сервером мониторинга php
  • 0Как запретить просмотр кода сайта
  • 0fullcalendar установить цвет отброшенного div
  • 0Синтаксически неправильно использовать html-конвертер в jsView следующим образом: data-link = «html {: property}» вместо data-link = «{html: property}»?
  • 1Как отдельный класс GUI будет взаимодействовать с классами логики?
  • 0объединить с двумя столбцами и получить значения полей из их внешнего ключа с помощью одного запроса SQL
  • 1Событие инициализации страницы framework7 не срабатывает
  • 1Как перечислить git коммиты для релиза Android?
  • 1Обнаружение исключений в родительском классе
  • 1Взаимодействие — вызывать ли родной из управляемых или наоборот
  • 0Выставленный литерал объекта службы Angular не обновляется?
  • 1Точность застряла на 50% керас
  • 0JQuery if заявление, основанное на ширине
  • 1Числовой эквивалент if / elif / else, который сохраняет последнее значение, если условие не выполняется
  • 0Мой первый столбец кода в простой консольной программе (c ++) заканчивается как мой последний столбец
  • 1Изменить шаблон панели приложения и селектора длинных списков из Viewmodel
  • 1Программа Android для отправки сообщений
  • 0С ++ Шаблонный Функтор
  • 1Промывка в репозиториях
  • 1Хранимая процедура CLR возвращает SqlDataReader, но тип метода void
  • 0Laravel 5 Internal Server Error 500 и TokenMismatchException для обновления базы данных с помощью AngularsJS
  • 0JQuery Удалить массив из массива массивов
  • 1javafx, реализующий и показывающий ListView
  • 1Как извлечь конкретное число в строку, окруженную цифрами и текстом C #
  • 0Выровняйте меню вправо, если lithth child равен 1 или 2
  • 0symfony2 рендеринг формы как тип формы
  • 1регистрация пользователя
  • 0Пожалуйста, подождите, пока панель загрузки при нажатии кнопки не отображается
  • 1Широковещательное сообщение на Java
  • 1Мониторинг файлов WMI с использованием C #
  • 0Найти первый элемент с классом, использовать класс, чтобы добавить элемент заголовка
  • 1Сгруппируйте столбец, если ни одна из строк не является уникальной, используя панд
  • 1Преобразовать исключение HttpException в ответ HTTP 404 (страница не найдена)
  • 1Укажите язык в Octokit.net для Gist
  • 1Умножение на Python ijk, почему мы используем следующую запись присваивания или строку кода?
  • 0.hasOwnProperty … и значение?
  • 0Могу ли я использовать функцию eval в этом случае?
  • 1Создание плавающего, редактируемого и прокручиваемого списка в Android
  • 1отсортировать массив с элементом, ближайшим к двум в середине и другими крайностями на другой стороне — js
  • 1Тренировочный набор для распознавания лиц
  • 1Воспроизведение SoftKeyboard на Android
  • 0Перегрузка перегруженного метода: есть ли упрощение?
  • 0Как удалить содержимое div?
  • 1Это правильная конфигурация Kafka Consumer — при этой настройке Kafka?
  • 0Html5 полноэкранный браузер Toggle Button

Сообщество Overcoder

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

palachevskiy

0 / 0 / 0

Регистрация: 15.05.2020

Сообщений: 9

1

15.05.2020, 16:57. Показов 7149. Ответов 4

Метки нет (Все метки)


Python
1
2
3
4
5
6
7
8
9
10
HeroPhrases = {}
 
while (line := input()) != "!ВСЁ":
    hero, phrase = line.split(": ")
    if hero not in HeroPhrases:
        HeroPhrases[hero] = []
    HeroPhrases[hero].append(phrase)
 
for hero, phrases in HeroPhrases.items():
    print(f"{hero} - {'; '.join(reversed(phrases))}")

./solution.py:3:12: E203 whitespace before ‘:’
./solution.py:3:13: E231 missing whitespace after ‘:’
./solution.py:3:13: E999 SyntaxError: invalid syntax
./solution.py:3:15: E251 unexpected spaces around keyword / parameter equals

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Эксперт Python

5403 / 3827 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

15.05.2020, 17:05

2

отфармотировать по стандарту PEP8

Может, сначала сдашь русский?

И еще: ты видел, что люди выкладывают сюда код в тегах Python кода, а не тупой нечитабельной лапшой?



1



Просто Лис

Эксперт Python

4830 / 3152 / 991

Регистрация: 17.05.2012

Сообщений: 9,186

Записей в блоге: 9

15.05.2020, 17:28

3

PyCharm -> ctrl+L



0



unfindable_404

Эксперт Python

683 / 466 / 204

Регистрация: 22.03.2020

Сообщений: 1,051

15.05.2020, 17:54

4

Дело не в PEP8. Код, который вы запускаете, поддерживается только Python3.8. Но вы запускаете его на Python более старой версии. Отсюда и ошибки. Я поправил.

Python
1
2
3
4
5
6
7
8
9
10
11
12
HeroPhrases = {}
 
line = input()
while line != "!ВСЁ":
    hero, phrase = line.split(": ")
    if hero not in HeroPhrases:
        HeroPhrases[hero] = []
    HeroPhrases[hero].append(phrase)
    line = input()
 
for hero, phrases in HeroPhrases.items():
    print(f"{hero} - {'; '.join(reversed(phrases))}")



2



Нарушитель

Эксперт PythonЭксперт Java

14040 / 8228 / 2485

Регистрация: 21.10.2017

Сообщений: 19,708

16.05.2020, 18:38

5

Цитата
Сообщение от Рыжий Лис
Посмотреть сообщение

PyCharm -> ctrl+L

Ctrl+Alt+L



2



Понравилась статья? Поделить с друзьями:

Читайте также:

  • E231 missing whitespace after как исправить
  • E225 ошибка принтера
  • E225 0001 canon ошибка
  • E22 ошибка стиральная машина bosch
  • E22 ошибка посудомоечная машина бош

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии