E251 unexpected spaces around keyword parameter equals как исправить

Disabling in Pylint

This can be disabled in Pylint with bad-whitespace:

$ cat a.py
myfunca(myargb = 3)

$ pylint a.py --reports=n
No config file found, using default configuration
************* Module a
C:  1, 0: No space allowed around keyword argument assignment
myfunca(myargb = 3)
               ^ (bad-whitespace)
C:  1, 0: Missing module docstring (missing-docstring)
E:  1, 0: Undefined variable 'myfunca' (undefined-variable)

$ pylint a.py  --disable bad-whitespace --reports=n
No config file found, using default configuration
************* Module a
C:  1, 0: Missing module docstring (missing-docstring)
E:  1, 0: Undefined variable 'myfunca' (undefined-variable)

Disabling in PEP8 Checker

For completeness, you can disable the same for pep8’s checker with E251:

$ pep8 a.py 
a.py:1:15: E251 unexpected spaces around keyword / parameter equals
a.py:1:17: E251 unexpected spaces around keyword / parameter equals

$ pep8 a.py --ignore=E251

Update — Info on suppressing just that message

AFAIK you can only disable messages down to the granularity of IDs in pylint, as all the whitespace has the same id bad-whitespace aka C0326 you can therefore either ignore all or none.

This is the code that checks if a message is disabled, as you see it only receives the id to check against:

def is_message_enabled(self, msg_descr, line=None, confidence=None):
    """return true if the message associated to the given message id is
    enabled

    msgid may be either a numeric or symbolic message id.
    """

When the message is added to the lint results, you can see that bad-whitespace is all that is passed in. The around and keyword argument assignment are simply arguments to the message.

warnings = []
if not any(good_space) and policies[0] == policies[1]:
    warnings.append((policies[0], 'around'))
else:
    for ok, policy, position in zip(good_space, policies, ('before', 'after')):
        if not ok:
            warnings.append((policy, position))
for policy, position in warnings:
    construct = _name_construct(token)
    count, state = _policy_string(policy)
    self.add_message('bad-whitespace', line=token[2][0],
                     args=(count, state, position, construct,
                           _underline_token(token)))

The arguments to the message are displayed using the formatting string:

'C0326': ('%s space %s %s %sn%s',
          'bad-whitespace',
          ('Used when a wrong number of spaces is used around an operator, '
           'bracket or block opener.'),

All that should help if you want to customize pylint to do what you want, and if so, a pull-request back to them would hopefully be well received.

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Closed

parasit opened this issue

Jun 20, 2010

· 6 comments

Closed

Problems with whitespaces E251 and E202

#12

parasit opened this issue

Jun 20, 2010

· 6 comments

Comments

@parasit

When i check source i got:
pep8.exe —show-source bazarviews.py
bazarviews.py:20:38: E251 no spaces around keyword / parameter equals
p = Category.objects.get(id = categoryId)
^
bazarviews.py:97:42: E202 whitespace before ‘)’
customData = json.dumps(resp)

But in both cases something is wrong, in first there are spaces, and in second dont.
Its error in checker or its my mistake?

Source in UTF-8 with unix (n) end of lines.
pep8 v. 0.5.0
python 2.6.1
OS: WinXP

@florentx

For the first one (E251), the message says that the correct syntax is:

p = Category.objects.get(id=categoryId)

For the E202 case, it complains about an extra whitespace before ‘)’.
If you can reproduce this issue with a very short snippet, please paste it here.
(or use a pastebin)

@bbrodriges

I’ve faced the same problem in my code.
Here’s a snippet:

def set_cookie(self, uid):

        '''Sets user cookie based on uid.'''

        response.set_cookie(
                '__utmb',
                uid,
                secret = self.COOKIE_SECRET_KEY,
                expires = time.time() + (3600 * 24 * 365),
                domain = '.mydomain.com',
                path = '/'
        )

And here is a traceback:

users.py:163:23: E251 no spaces around keyword / parameter equals
                secret = self.COOKIE_SECRET_KEY,
                      ^

pep8 0.6.1, python 2.7.2

@bbrodriges

My mistake, I have found error.

@franciscolourenco

@sigmavirus24

@aristidesfl when using keyword arguments/parameters in function calls you should not have spaces around the equal sign as per PEP8.

It should be

# snip
secret=self.COOKIE_SECRET_KEY,
expires=time.time() + (3600 * 24 * 365),
domain='.mydomain.com',
path='/'

I hope that helps.

@bbrodriges

У меня есть код: (python3, максимальная длина строки 120)

self.command(
        parametr1, parametr2, self.object1(
                                           need_to_be_rewrited=self.need_to_be_rewrited
                                           )

Но flake8 выдаёт исключение

E501 line too long (122 > 120 characters)

Я попробовал перенести код так:

self.command(
        parametr1, parametr2, self.object1(
                                           need_to_be_rewrited= 
                                           self.need_to_be_rewrited
                                           )

и получил предупреждение flake8:

E251 unexpected spaces around keyword / parameter equals

Помогите, пожалуйста!

Python’s PEP8 code specification, so record the common PEP8 code specification problems and solutions, learn it, and continue to update when you encounter it, develop good habits, and write standardized code!

PEP 8: no newline at end of file

Solution: You need to start a new line at the end of the code and move the cursor to the last carriage return

  • PEP 8: indentation is not a multiple of four
    Solution: Indent is not a multiple of 4, check indent

  • PEP 8: over-indented
    Solution: Excessive indentation, check indentation

  • PEP 8: missing whitespace after’,’
    Solution: There are fewer spaces after the comma, just add spaces, similar to the semicolon or colon after the missing spaces

  • PEP 8: multiple imports on one line
    Solution: Do not refer to multiple libraries in one sentence, for example:import socket, urllib.errorIt is best written as:import socket import urllib.error

  • PEP 8: blank line at end of line
    Solution: There are more spaces at the end of the code, just delete the spaces

  • PEP 8: at least two spaces before inline comment
    Solution: There must be at least two spaces between the code and the comment

  • PEP 8: block comment should start with ‘#’
    Solution: The comment should start with # plus a space

  • PEP 8: inline comment should start with ‘#’
    Solution: The comment should start with # plus a space

  • PEP 8: module level import not at top of file
    Solution: import is not at the top of the file, there may be other code before

  • PEP 8: expected 2 blank lines,found 0
    Solution: Two blank lines are needed, add two blank lines

  • PEP 8: function name should be lowercase
    Solution: Change the function name to lower case

  • PEP 8: missing whitespace around operator
    Solution: Operators (’=’, ‘>’, ‘<’, etc.) lack spaces before and after, just add

  • PEP 8: unexpected spaces around keyword / parameter equals
    Solution: Unexpected spaces appear around the keyword / parameter equal sign, just remove the spaces

  • PEP 8: multiple statements on one line (colon)
    Solution: The multi-line statement is written to one line, for example:if x == 2: print('OK')Write in two lines

  • PEP 8: line too long (82 > 79 characters)
    Solution: The maximum length limit of each line is exceeded 79

  • PEP 8: Simplify chained comparison
    can simplify chain comparisons (for example:if a >= 0 and a <= 9: Can be abbreviated as:if 0 <= a <= 9:


  • If you want to selectively ignore the warning message of the PEP8 code style, you can use the following methods: (Cultivate good habits and write standardized code! It is not recommended to ignore!)

    ①Move the mouse to the place where the warning message appears, pressalt+Enter, Choose to ignore (Ignore) this error:

    ②Select one by oneFile — Settings — Editor — Inspections, Found under PythonPEP8 coding style violation Options, in the lower right cornerIgnore errors Click the plus sign to add the warning message ID that needs to be ignored (see the appendix for ID information), for example, you want to ignoreindentation contains mixed spaces and tabsFor this warning, just add its ID:E101 Just

    Appendix: All warning messages and corresponding IDs, official address: https://pep8.readthedocs.io/en/latest/intro.html#error-codes

    code sample message
    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)
    E117 over-indented
    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

    Я начинающий 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Получить имя класса документа
    • 0Испытательный корпус по угловой директиве Karma не компилирует HTML
    • 1Просмотр полноэкранного изображения после нажатия кнопки onClick
    • 0Есть ли способ добавить атрибут только в 1 строку в SQL?
    • 0Преобразуйте MySql InputStream в byte []
    • 0пакет udp не получен в QThread
    • 1Как я могу использовать AddOrUpdate .NET ConcurrentDictionary с моим пользовательским POCO?
    • 1Генерация URL с параметрами из переменных JS в TWIG
    • 1Как отсортировать определенные элементы в ArrayList в Java?
    • 0Проблема, связанная с браузером Chrome
    • 1Вызов Image.FromFile выдает исключение Out of memory
    • 0Компиляция и использование OpenCV
    • 0Я получаю «Усеченное неверное значение даты и времени:« 0000-00-00 »» даже при выключенном строгом режиме.
    • 1Как получить пользователей из списка LiveData для отображения в Spinner с использованием базы данных комнат
    • 0Получить текст всех вариантов выбора элементов?
    • 1Неверно отформатированный десятичный код дает неверную ошибку
    • 0Коллекции форм ZF2 Zend Form FormElementManager :: get не удалось получить или создать экземпляр для
    • 1Python3 не удалось преобразовать str в dict или json
    • 0Сравните время Python с форматом времени MySQL
    • 1C # объект или массив
    • 1Маршрутизатор не определен Node.js
    • 0Переадресация вкладок плагинов с первой вкладки на вторую
    • 1notify () против notifyAll ()?
    • 0вставлять и удалять целые числа на лету
    • 0Правильное использование родительских свойств
    • 1Проблемы с настройкой GUI
    • 1добавить текстовую область в Java из другого файла Java
    • 0angular ng-selected, выберите текущий родительский $ index
    • 1Java или Scala RFC5987
    • 1Ошибка развертывания проекта asmx в Elastic Beanstalk
    • 0Codeigniter — обязательное поле для проверки формы 2 с несоответствующим значением
    • 0Ant генерирует html href список из набора файлов, добавляет тег для каждой строки
    • 0Неправильное сравнение строк с использованием strtok ()
    • 0Как глубоко скопировать конструктор с уникальным указателем внутри класса шаблона?
    • 1Как я могу получить в своем API дочерний класс?
    • 0Nodejs Sequelize отношения не работают
    • 0Перетащите изображение / текст / имя файла на страницу Firefox
    • 0Слайд-тумблер на динамическом контенте
    • 0Невозможно загрузить файл на сервер (AngularJS и Perl)
    • 1возникли проблемы с совместимостью заданий?
    • 1Передача значений из фрагмента в действие с использованием дополнительных функций устанавливает только нулевые значения
    • 1Проблема создания метки времени (несколько) во время летнего времени
    • 0Сортировка столбцов таблицы в AngularJS
    • 0Простой селектор jQuery
    • 1Как поделиться изображением Создано растровое изображение
    • 0Как вызвать шаблонный метод [duplicate]
    • 0PHP отображает имена элементов массива
    • 1Привязка функции обратного вызова при использовании Async Waterfall
    • 0Сохранить массив элементов SDL_Surface в классе?
    • 0Имя поля / столбца MYSQL и PHP как переменная

    Сообщество Overcoder

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