Как проверить код на ошибки python

Рассмотрим популярные инструменты для анализа кода Python и подробно расскажем об их специфике и основных принципах работы.

Рассмотрим популярные инструменты для анализа кода Python и подробно расскажем об их специфике и основных принципах работы.

Инструменты для анализа кода Python. Часть 1

Автор: Валерий Шагур, teacher assistance на курсе Программирование на Python

Высокая стоимость ошибок в программных продуктах предъявляет повышенные
требования к качеству кода. Каким критериям должен соответствовать хороший код?
Отсутствие ошибок, расширяемость, поддерживаемость, читаемость и наличие документации. Недостаточное внимание к любому из этих критериев может привести к появлению новых ошибок или снизить вероятность обнаружения уже существующих. Небрежно написанный или чересчур запутанный код, отсутствие документации напрямую влияют на время исправления найденного бага, ведь разработчику приходится заново вникать в код. Даже такие, казалось бы, незначительные вещи как неправильные имена переменных или отсутствие форматирования могут сильно влиять на читаемость и понимание кода.

Командная работа над проектом еще больше повышает требования к качеству кода, поэтому важным условием продуктивной работы команды становится описание формальных требований к написанию кода. Это могут быть соглашения, принятые в языке программирования, на котором ведется разработка, или собственное (внутрикорпоративное) руководство по стилю. Выработанные требования к оформлению кода не исключают появления «разночтений» среди разработчиков и временных затрат на их обсуждение. Кроме этого, соблюдение выработанных требований ложится на плечи программистов в виде дополнительной нагрузки. Все это привело к появлению инструментов для проверки кода на наличие стилистических и логических ошибок. О таких инструментах для языка программирования Python мы и поговорим в этой статье.

Анализаторы и автоматическое форматирование кода

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

И первая, и вторая группы включают в себя как простые утилиты командной строки для решения узкоспециализированных задач (например, проверка docstring или сортировка импортов), так и богатые по возможностям библиотеки, объединяющие в себе более простые утилиты. Средства анализа кода из первой группы принято называть линтерами (linter). Название происходит от lint — статического анализатора для языка программирования Си и со временем ставшего нарицательным. Программы второй группы называют форматировщиками (formatter).

Даже при поверхностном сравнении этих групп видны особенности работы с ними. При применении линтеров программисту, во-первых, необходимо писать код с оглядкой, дабы позже не исправлять найденные ошибки. И во вторых, принимать решение по поводу обнаруженных ошибок — какие требуют исправления, а какие можно проигнорировать. Форматировщики, напротив, автоматизируют процесс исправления ошибок, оставляя программисту возможность осуществлять контроль.

Часть 1

  • pycodestyle
  • pydocstyle
  • pyflakes
  • pylint
  • vulture

Часть 2

  • flake8
  • prospector
  • pylama
  • autopep8
  • yapf
  • black

Соглашения принятые в статье и общие замечания

Прежде чем приступить к обзору программ, мы хотели бы обратить ваше внимание на несколько важных моментов.

Версия Python: во всех примерах, приведенных в статье, будет использоваться третья версия языка программирования Python.

Установка всех программ в обзоре практически однотипна и сводится к использованию пакетного менеджера pip.

$ python3.6 -m pip install --upgrade <package_name>

Некоторые из библиотек имеют готовые бинарные пакеты в репозиториях дистрибутивов linux или возможность установки с использованием git. Тем не менее для большей определенности и возможности повторения примеров из статьи, установка будет производится с помощью pip.

Об ошибках: стоит упомянуть, что говоря об ошибках, обнаруживаемых анализаторами кода, как правило, имеют в виду два типа ошибок. К первому относятся ошибки стиля (неправильные отступы, длинные строки), ко второму — ошибки в логике программы и ошибки синтаксиса языка программирования (опечатки при написании названий стандартных функций, неиспользуемые импорты, дублирование кода). Существуют и другие виды ошибок, например — оставленные в коде пароли или высокая цикломатическая сложность.

Тестовый скрипт: для примеров использования программ мы создали простенький по содержанию файл example.py. Мы сознательно не стали делать его более разнообразным по наличию в нем ошибок. Во-первых, добавление листингов с выводом некоторых анализаторов в таком случае сильно “раздуло” бы статью. Во-вторых, у нас не было цели детально показать различия в “отлове” тех или иных ошибок для каждой из утилит.

Содержание файла example.py:

import os
import notexistmodule

def Function(num,num_two):
return num

class MyClass:
"""class MyClass """

def __init__(self,var):
self.var=var

def out(var):
print(var)


if __name__ == "__main__":
my_class = MyClass("var")
my_class.out("var")
notexistmodule.func(5)

В коде допущено несколько ошибок:

  • импорт неиспользуемого модуля os,
  • импорт не существующего модуля notexistmodule,
  • имя функции начинается с заглавной буквы,
  • лишние аргументы в определении функции,
  • отсутствие self первым аргументом в методе класса,
  • неверное форматирование.

Руководства по стилям: для тех, кто впервые сталкивается с темой оформления кода, в качестве знакомства предлагаем прочитать официальные руководства по стилю для языка Python PEP8 и PEP257. В качестве примера внутрикорпоративных соглашений можно рассмотреть Google Python Style Guide — https://github.com/google/styleguide/blob/gh-pages/pyguide.md

Pycodestyle

Pycodestyle — простая консольная утилита для анализа кода Python, а именно для проверки кода на соответствие PEP8. Один из старейших анализаторов кода, до 2016 года носил название pep8, но был переименован по просьбе создателя языка Python Гвидо ван Россума.

Запустим проверку на нашем коде:

$ python3 -m pycodestyle example.py 
example.py:4:1: E302 expected 2 blank lines, found 1
example.py:4:17: E231 missing whitespace after ','
example.py:7:1: E302 expected 2 blank lines, found 1
example.py:10:22: E231 missing whitespace after ','
example.py:11:17: E225 missing whitespace around operator

Лаконичный вывод показывает нам строки, в которых, по мнению анализатора, есть нарушение соглашений PEP8. Формат вывода прост и содержит только необходимую информацию:

<имя файла>: <номер строки> :<положение символа>: <код и короткая расшифровка ошибки>

Возможности программы по проверке соглашений ограничены: нет проверок на правильность именования, проверка документации сводится к проверки длины docstring. Тем не менее функционал программы нельзя назвать “спартанским”, он позволяет настроить необходимый уровень проверок и получить различную информацию о результатах анализа. Запуск с ключом —statistics -qq выводит статистику по ошибкам:

$ python3 -m pycodestyle --statistics -qq example.py 
1 E225 missing whitespace around operator
2 E231 missing whitespace after ','
2 E302 expected 2 blank lines, found 1

Более наглядный вывод можно получить при использовании ключа —show-source. После каждого сообщения об ошибке будет выведена строка исходного кода, в которой содержится ошибка.

$ python3 -m pycodestyle --show-source example.py 
example.py:4:1: E302 expected 2 blank lines, found 1
def Function(num,num_two):
^
example.py:4:17: E231 missing whitespace after ','
def Function(num,num_two):
^
example.py:7:1: E302 expected 2 blank lines, found 1
class MyClass:
^
example.py:10:22: E231 missing whitespace after ','
def __init__(self,var):
^
example.py:11:17: E225 missing whitespace around operator
self.var=var
^

Если есть необходимость посмотреть, какие из соглашений PEP8 были нарушены, используйте ключ — show-pep8. Программа выведет список всех проверок с выдержками из PEP8 для случаев нарушений. При обработке файлов внутри директорий предусмотрена возможность фильтрации по шаблону. Pycodestyle позволяет сохранять настройки поиска в конфигурационных файлах как глобально, так и на уровне проекта.

Pydocstyle

Утилиту pydocstyle мы уже упоминали в статье Работа с документацией в Python: поиск информации и соглашения. Pydocstyle проверяет наличие docstring у модулей, классов, функций и их соответствие официальному соглашению PEP257.

$ python3 -m pydocstyle example.py
example.py:1 at module level:
D100: Missing docstring in public module
example.py:4 in public function `Function`:
D103: Missing docstring in public function
example.py:7 in public class `MyClass`:
D400: First line should end with a period (not 's')
example.py:7 in public class `MyClass`:
D210: No whitespaces allowed surrounding docstring text
example.py:10 in public method `__init__`:
D107: Missing docstring in __init__
example.py:13 in public method `out`:
D102: Missing docstring in public method

Как мы видим из листинга, программа указала нам на отсутствие документации в определениях функции, методов класса и ошибки оформления в docstring класса. Вывод можно сделать более информативным, если использовать ключи —explain и —source при вызове программы. Функционал pydocstyle практически идентичен описанному выше для pycodestyle, различия касаются лишь названий ключей.

Pyflakes

В отличие от уже рассмотренных инструментов для анализа кода Python pyflakes не делает проверок стиля. Цель этого анализатора кода — поиск логических и синтаксических ошибок. Разработчики pyflakes сделали упор на скорость работы программы, безопасность и простоту. Несмотря на то, что данная утилита не импортирует проверяемый файл, она прекрасно справляется c поиском синтаксических ошибок и делает это быстро. С другой стороны, такой подход сильно сужает область проверок.
Функциональность pyflakes — “нулевая”, все что он умеет делать — это выводить результаты анализа в консоль:

$ python3 -m pyflakes example.py 
example.py:1: 'os' imported but unused

В нашем тестовом скрипте, он нашел только импорт не используемого модуля os. Вы можете самостоятельно поэкспериментировать с запуском программы и передачей ей в качестве параметра командной строки Python файла, содержащего синтаксические ошибки. Данная утилита имеет еще одну особенность — если вы используете обе версии Python, вам придется установить отдельные утилиты для каждой из версий.

Pylint

До сих пор мы рассматривали утилиты, которые проводили проверки на наличие либо стилистических, либо логических ошибок. Следующий в обзоре статический инструмент для анализа кода Python — Pylint, который совместил в себе обе возможности. Этот мощный, гибко настраиваемый инструмент для анализа кода Python отличается большим количеством проверок и разнообразием отчетов. Это один из самых “придирчивых” и “многословных” анализаторов кода. Анализ нашего тестового скрипта выдает весьма обширный отчет, состоящий из списка найденных в ходе анализа недочетов, статистических отчетов, представленных в виде таблиц, и общей оценки кода:

$ python3.6 -m pylint --reports=y text example.py
************* Module text
/home/ququshka77/.local/lib/python3.6/site-packages/pylint/reporters/text.py:79:22: W0212: Access to a protected member _splitstrip of a client class (protected-access)
************* Module example
example.py:4:16: C0326: Exactly one space required after comma
def Function(num,num_two):
                           ^ (bad-whitespace)
example.py:10:21: C0326: Exactly one space required after comma
    def __init__(self,var):
                             ^ (bad-whitespace)
example.py:11:16: C0326: Exactly one space required around assignment
        self.var=var
                    ^ (bad-whitespace)
example.py:1:0: C0111: Missing module docstring (missing-docstring)
example.py:2:0: E0401: Unable to import 'notexistmodule' (import-error)
example.py:4:0: C0103: Function name "Function" doesn't conform to snake_case naming style (invalid-name)
example.py:4:0: C0111: Missing function docstring (missing-docstring)
example.py:4:17: W0613: Unused argument 'num_two' (unused-argument)
example.py:13:4: C0111: Missing method docstring (missing-docstring)
example.py:13:4: E0213: Method should have "self" as first argument (no-self-argument)
example.py:7:0: R0903: Too few public methods (1/2) (too-few-public-methods)
example.py:18:4: C0103: Constant name "my_class" doesn't conform to UPPER_CASE naming style (invalid-name)
example.py:19:4: E1121: Too many positional arguments for method call (too-many-function-args)
example.py:1:0: W0611: Unused import os (unused-import)

Report
======
112 statements analysed.

Statistics by type
+----------+----------+---------------+-------------+-------------------+---------------+
|type     |number      |old number        |difference      |%documented       |%badname |
+======+======+========+========+===========+========+
|module   |2           |2                 |=               |50.00             |0.00            |
+-----------+----------+---------------+-------------+-------------------+---------------+
|class    |5           |5                 |=               |100.00            |0.00            |
+-----------+----------+---------------+-------------+-------------------+---------------+
|method   |11          |11                |=               |90.91             |0.00            |
+-----------+----------+---------------+-------------+-------------------+---------------+
|function |4           |4                 |=               |75.00             |25.00          |
+-----------+----------+---------------+-------------+-------------------+---------------+

External dependencies
::
    pylint 
      -interfaces (text)
      -reporters (text)
      | -ureports 
      |   -text_writer (text)
      -utils (text)


Raw metrics
+-------------+----------+-------+-----------+-------------+
|type        |number |%     |previous    |difference |
+=======+======+=====+=====+========+
|code        |128    |48.30 |128         |=               |
+-------------+----------+--------+-----------+------------+
|docstring   |84     |31.70 |84          |=               |
+-------------+----------+--------+-----------+------------+
|comment     |16     |6.04  |16          |=               |
+-------------+----------+--------+-----------+------------+
|empty       |37     |13.96 |37          |=               |
+-------------+----------+--------+-----------+------------+

Duplication
+-------------------------------+------+------------+-------------+
|                            |now      |previous      |difference |
+=================+=====+======+========+
|nb duplicated lines         |0        |0             |=              |
+-------------------------------+-------+------------+------------+
|percent duplicated lines    |0.000    |0.000         |=              |
+-------------------------------+-------+------------+------------+

Messages by category
+--------------+----------+-----------+-------------+
|type            |number |previous |difference |
+========+======+======+========+
|convention      |8       |8       |=               |
+--------------+----------+-----------+-------------+
|refactor        |1       |1       |=               |
+--------------+-----------+----------+-------------+
|warning         |3       |3       |=               |
+--------------+-----------+----------+-------------+
|error           |3       |3       |=               |
+--------------+-----------+----------+-------------+

% errors / warnings by module
+-----------+--------+-----------+----------+--------------+
|module   |error    |warning |refactor |convention   |
+======+=====+======+======+========+
|example  |100.00   |66.67   |100.00   |100.00       |
+-----------+---------+----------+-----------+-------------+
|text     |0.00     |33.33   |0.00     |0.00         |
+-----------+---------+----------+-----------+-------------+

Messages
+-----------------------------+----------------+
|message id                  |occurrences |
+=================+=========+
|missing-docstring           |3                 |
+-----------------------------+----------------+
|bad-whitespace              |3                 |
+------------------------------+---------------+
|invalid-name                |2                 |
+------------------------------+---------------+
|unused-import               |1                 |
+------------------------------+---------------+
|unused-argument             |1                 |
+------------------------------+---------------+
|too-many-function-args      |1                 | 
+------------------------------+---------------+
|too-few-public-methods      |1                 |
+------------------------------+---------------+
|protected-access            |1                 |
+------------------------------+---------------+
|no-self-argument            |1                 |
+------------------------------+---------------+
|import-error                |1                 |
+------------------------------+---------------+

------------------------------------------------------------------------------------------
Your code has been rated at 7.59/10 (previous run: 7.59/10, +0.00)

Программа имеет свою внутреннюю маркировку проблемных мест в коде:

[R]efactor — требуется рефакторинг,
[C]onvention — нарушено следование стилистике и соглашениям,
[W]arning — потенциальная ошибка,
[E]rror — ошибка,
[F]atal — ошибка, которая препятствует дальнейшей работе программы.

Для вывода подробного отчета мы использовали ключ командной строки —reports=y.
Более гибко настроить вывод команды позволяют разнообразные ключи командной строки. Настройки можно сохранять в файле настроек rcfile. Мы не будем приводить подробное описание ключей и настроек, для этого есть официальная документация — https://pylint.readthedocs.io/en/latest/index.html#, остановимся лишь на наиболее интересных, с нашей точки зрения, возможностях утилиты:

— Генерация файла настроек (—generate-rcfile). Позволяет не писать конфигурационный файл с нуля. В созданном rcfile содержатся все текущие настройки с подробными комментариями к ним, вам остается только отредактировать его под собственные требования.

— Отключение вывода в коде. При редактировании кода есть возможность вставить блокирующие вывод сообщений комментарии. Чтобы продемонстрировать это, в определение функции в файле примера example.py добавим строку:

# pylint: disable=unused-argument

и запустим pylint. Из результатов проверки “исчезло” сообщение:

example.py:4:17: W0613: Unused argument 'num_two' (unused-argument)

— Создание отчетов в формате json (—output-format=json). Полезно, если необходимо сохранение или дальнейшая обработка результатов работы линтера. Вы также можете создать собственный формат вывода данных.

— Параллельный запуск (-j 4). Запуск в нескольких параллельных потоках на многоядерных процессорах сокращает время проверки.

— Встроенная документация. Вызов программы с ключом —help-msg=<key> выведет справку по ключевому слову key. В качестве ключевого слова может быть код сообщения (например: E0401) или символическое имя сообщения (например: import-error). Ниже приведен листинг получения справки по ключу import-error:

$ python3.6 -m pylint --help-msg=import-error
:import-error (E0401): *Unable to import %s*
Used when pylint has been unable to import a module. This message belongs to
the imports checker.

— Система оценки сохраняет последний результат и при последующих запусках показывает изменения, что позволяет количественно оценить прогресс исправлений.

— Плагины — отличная возможность изменять поведение pylint. Их применение может оказаться полезным в случаях, когда pylint неправильно обрабатывает код и есть “ложные” срабатывания, или когда требуется отличный от стандартного формат вывода результатов.

Vulture

Vulture — небольшая утилита для поиска “мертвого” кода в программах Python. Она использует модуль ast стандартной библиотеки и создает абстрактные синтаксические деревья для всех файлов исходного кода в проекте. Далее осуществляется поиск всех объектов, которые были определены, но не используются. Vulture полезно применять для очистки и нахождения ошибок в больших базовых кодах.

Продолжение следует

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

Еще статьи по Python

  • 26 полезных возможностей Python: букварь разработки от А до Z;
  • ТОП-15 трюков в Python 3, делающих код понятнее и быстрее;
  • Новый Python: 7 возможностей, которые вам понравятся;
  • Крупнейшая подборка Python-каналов на Youtube;
  • Изучение Python: ТОП-10 вопросов разной направленности.

Анализ кода в Python может быть трудной темой, но очень полезной в тех случаях, когда вам нужно повысить производительность вашей программы. Существует несколько анализаторов кода для Python, которые вы можете использовать для проверки своего кода и выяснить, соответствует ли он стандартам. Самым популярным можно назвать pylint. Он очень удобен в настойках и подключениях. Он также проверяет ваш код на соответствие с PEP8, официальным руководством по стилю ядра Python, а также ищет программные ошибки. Обратите внимание на то, что pylint проверяет ваш код на большую часть стандартов PEP8, но не на все. Также мы уделим наше внимание тому, чтобы научиться работать с другим анализатором кода, а именно pyflakes.

Начнем с pylint

Пакет pylint не входит в Python, так что вам нужно будет посетить PyPI (Python Package Index), или непосредственно сайт пакета для загрузки. Вы можете использовать следующую команду, которая сделает всю работу за вас:

Если все идет по плану, то pylint установится, и мы сможем пойти дальше.

Анализ вашего кода

После установки pylint вы можете запустить его в командной строке, без каких либо аргументов, что бы увидеть, какие опции он принимает. Если это не сработало, можете прописать полный путь, вот так:

c:Python34Scriptspylint

Теперь нам нужен какой-нибудь код для анализа. Вот часть кода, которая содержит четыре ошибки. Сохраните её в файле под названием crummy_code.py:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import sys

class CarClass:

    «»»»»»

    def __init__(self, color, make, model, year):

        «»»Constructor»»»

        self.color = color

        self.make = make

        self.model = model

        self.year = year

        if «Windows» in platform.platform():

            print(«You’re using Windows!»)

        self.weight = self.getWeight(1, 2, 3)

    def getWeight(this):

        «»»»»»

        return «2000 lbs»

Можете увидеть ошибки не запуская код? Давайте посмотрим, может ли pylint найти их!

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Паблик VK

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

После запуска этой команды вы увидите большую выдачу на вашем экране. Вот частичный пример:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

c:py101>c:Python34Scriptspylint crummy_code.py

No config file found, using default configuration

************* Module crummy_code

C: 2, 0: Trailing whitespace (trailing-whitespace)

C: 5, 0: Trailing whitespace (trailing-whitespace)

C: 12, 0: Trailing whitespace (trailing-whitespace)

C: 15, 0: Trailing whitespace (trailing-whitespace)

C: 17, 0: Trailing whitespace (trailing-whitespace)

C: 1, 0: Missing module docstring (missing-docstring)

C: 3, 0: Empty class docstring (empty-docstring)

C: 3, 0: Old-style class defined. (old-style-class)

E: 13,24: Undefined variable ‘platform’ (undefined-variable)

E: 16,36: Too many positional arguments for function call (too-many-function-args)

C: 18, 4: Invalid method name «getWeight» (invalid-name)

C: 18, 4: Empty method docstring (empty-docstring)

E: 18, 4: Method should have «self» as first argument (no-self-argument)

R: 18, 4: Method could be a function (no-self-use)

R: 3, 0: Too few public methods (1/2) (too-few-public-methods)

W: 1, 0: Unused import sys (unused-import)

Давайте немного притормозим и разберемся. Сначала нам нужно понять, что означают буквы:

  • С – конвенция (convention)
  • R – рефакторинг (refactor)
  • W – предупреждение (warning)
  • E – ошибка (error)

Наш pylint нашел 3 ошибки, 4 проблемы с конвенцией, 2 строки, которые нуждаются в рефакторинге и одно предупреждение. Предупреждение и 3 ошибки – это как раз то, что я искал. Мы попытаемся исправить этот код и устранить ряд проблем. Для начала мы наведем порядок в импортах, и изменить функцию getWeight на get_weight, в связи с тем, что camelCase не используется в названиях методов. Нам также нужно исправить вызов get_weight, чтобы он передавал правильное количество аргументов и исправить его, чтобы “self” выступал в качестве первого аргумента. Взглянем на новый код:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

# crummy_code_fixed.py

import platform

class CarClass:

    «»»»»»

    def __init__(self, color, make, model, year):

        «»»Constructor»»»

        self.color = color

        self.make = make

        self.model = model

        self.year = year

        if «Windows» in platform.platform():

            print(«You’re using Windows!»)

        self.weight = self.get_weight(3)

    def get_weight(self, this):

        «»»»»»

        return «2000 lbs»

Давайте запустим новый код с pylint и посмотрим, насколько успешно мы провели работу. Для краткости, мы еще раз рассмотрим первую часть:

c:py101>c:Python34Scriptspylint crummy_code_fixed.py

No config file found, using default configuration

************* Module crummy_code_fixed

C: 1,0: Missing docstring

C: 4,0: CarClass: Empty docstring

C: 21,4: CarClass.get_weight: Empty docstring

W: 21,25: CarClass.get_weight: Unused argument ‘this’

R: 21,4: CarClass.get_weight: Method could be a function

R: 4,0: CarClass: Too few public methods (1/2)

Как мы видим, это очень помогло. Если мы добавим docstrings, мы можем снизить количество ошибок вдвое. Теперь мы готовы перейти к pyflakes!

Работаем с pyflakes

Проект pyflakes это часть чего-то, что называется Divmod Project. Pyflakes на самом деле не выполняет проверяемый код также, как и pylint. Вы можете установить pyflakes при помощи pip, easy_install, или из другого источника.

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

Мы начнем с запуска pyflakes в изначальной версии той же части кода, которую мы использовали для проверки pylint. Вот и он:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import sys

class CarClass:

    «»»»»»

    def __init__(self, color, make, model, year):

        «»»Constructor»»»

        self.color = color

        self.make = make

        self.model = model

        self.year = year

        if «Windows» in platform.platform():

            print(«You’re using Windows!»)

        self.weight = self.getWeight(1, 2, 3)

    def getWeight(this):

        «»»»»»

        return «2000 lbs»

Как мы отмечали в предыдущем разделе, в этом поломанном коде четыре ошибки, три из которых препятствуют работе программы. Давайте посмотрим, что же pyflakes может найти. Попытайтесь запустить данную команду и на выходе вы должны получить следующее:

c:py101>c:Python34Scriptspyflakes.exe crummy_code.py

crummy_code.py:1: ‘sys’ imported but unused

crummy_code.py:13: undefined name ‘platform’

Несмотря на суперски быструю скорость возврата выдачи, pyflakes не нашел все ошибки. Вызов метода getWeight передает слишком много аргументов, также метод getWeight сам по себе определен некорректно, так как у него нет аргумента self. Что-же, вы, собственно, можете называть первый аргумент так, как вам угодно, но в конвенции он всегда называется self. Если вы исправили код, оперируя тем, что вам сказал pyflakes, код не заработает, несмотря на это.

Подведем итоги

Следующим шагом должна быть попытка запуска pylint и pyflakes в вашем собственном коде, либо же в пакете Python, вроде SQLAlchemy, после чего следует изучить полученные в выдаче данные. Вы можете многое узнать о своем коде, используя данные инструменты. pylint интегрирован с Wingware, Editra, и PyDev. Некоторые предупреждения pylint могут показаться вам раздражительными, или не особо уместными. Существует несколько способов избавиться от таких моментов, как предупреждения об устаревании, через опции командной строки. Вы также можете использовать -generate-rcfile для создания примера файла config, который поможет вам контролировать работу pylint. Обратите внимание на то, что pylint и pyflakes не импортируют ваш код, так что вам не нужно беспокоиться о нежелательных побочных эффектах.

Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.

E-mail: vasile.buldumac@ati.utm.md

Образование
Universitatea Tehnică a Moldovei (utm.md)

  • 2014 — 2018 Технический Университет Молдовы, ИТ-Инженер. Тема дипломной работы «Автоматизация покупки и продажи криптовалюты используя технический анализ»
  • 2018 — 2020 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»

Линтеры

В сообществе Python, как и в любой другой группе людей, существует некое
коллективное знание. Множество людей прошлось по всем возможным граблям
и получило опыт через набитые шишки. Затем через какое-то время,
благодаря выступлениям на конференциях, официальным заявлениям,
документам, статьям в блогах, код-ревью и личному общению,
это знание стало коллективным. Теперь мы просто называем его
“хорошими практиками”.

К таким хорошим практикам можно отнести, например, следующие.

  • Форматировать код по PEP8
    — если этого не делать, то другим людям будет намного сложнее понимать
    ваш код; в плохо оформленном коде сложнее увидеть суть,
    потому что мозг постоянно отвлекается на не несущие смысловой нагрузки
    особенности оформления.
  • Не допускать объявленных, но неиспользуемых переменных/функций/импортов
    — опять же, это усложняет восприятие кода; читателю потребуется потратить
    время на то, чтобы осознать, что вот на эту сущность обращать внимания не
    нужно.
  • Писать короткие функции — слишком сложные функции с большим
    количеством ветвлений и циклов тяжело понимать.
  • Не использовать изменяемый объект в качестве значения аргумента
    функции по умолчанию — иначе в результате можно получить
    очень неожиданные эффекты.

Соблюдать (и даже просто помнить) все хорошие практики — не самая простая
задача. Зачастую люди плохо справляются с тем, чтобы отсчитывать пробелы
и контролировать переменные, и вообще склонны допускать ошибки по
невнимательности. Таковы люди, ничего не поделаешь. Машины, наоборот,
прекрасно справляются с такими хорошо определёнными задачами, поэтому
появились инструменты, которые контролируют следование хорошим практикам.

В компилируемых языках ещё на этапе компиляции программист может получить
по щщам первый полезный фидбэк о написанном коде.
Компилятор проверит, что код валиден и может быть скомпилирован, а также может
выдать предупреждения и рекомендации, как сделать код лучше или читаемее.
Т.к. Python является интерпретируемым языком, где этап компиляции как таковой
отсутствует, линтеры особенно полезны. На самом деле, это очень важно и
круто — узнать, что твой код как минимум является валидным Python-кодом,
даже не запуская его.

В этом посте я рассмотрю два самых популярных линтера для Python:

  • flake8;
  • pylint.

Термин “lint” впервые начал использоваться в таком значении в 1979 году.
Так называлась программа для статического анализа кода на C,
которая предупреждала об использовании непортабельных на другие архитектуры
языковых конструкций. С тех пор “линтерами” называют любые статические
анализаторы кода, которые помогают находить распространённые ошибки, делать
его однообразным и более читаемым. А названо оно «lint» в честь вот такой
штуки:

lint roller

flake8

flake8 — это утилита-комбайн, которая органично объединяет в себе несколько
других анализаторов кода (pycodestyle, pyflakes и mccabe), а также
имеет огромную экосистему плагинов, которые могут добавить к стандартной
поставке ещё кучу различных проверок. На данный момент, это самый
популярный линтер для Python-кода. Кроме того, он предельно прост в
настройке и использовании.

Установка

flake8 устанавливается, как и любой другой Python-пакет,
через pip. Внутри виртуального окружения проекта выполните:

Если вы пользуетесь pipenv, то flake8 нужно устанавливать
как dev-зависимость (ведь для работы программы линтер не нужен,
он нужен только для разработчика):

$ pipenv install --dev flake8

Аналогично с poetry:

$ poetry add --dev flake8

Проверим установку:

$ flake8 --version
3.8.1 (mccabe: 0.6.1, pycodestyle: 2.6.0, pyflakes: 2.2.0) CPython 3.8.2 on Linux

Использование

Для работы flake8 нужно просто указать файл или директорию, которые
нужно проверять, например:

# проверить один файл
$ flake8 file.py

# проверить директорию рекурсивно 
$ flake8 src/

# проверить текущую директорию рекурсивно
$ flake8 .

Давайте для демонстрации попытаемся написать программу с как можно большим
количеством “плохих практик”:

Возможно, вам не видно всего, но в этом коде точно есть следующие «запахи кода»:

  • import * — импортирование всех имен из модуля, хотя используется
    из них только одно;
  • import itertools — ненужный импорт;
  • во множестве мест стоят лишние или отсутствующие пробелы;
  • название функции написано в стиле PascalCase;
  • в некоторых местах используются табы для отступов;
  • используется список (изменяемый объект) в качестве значения аргумента
    функции по умолчанию;
  • используется слишком “широкое” выражение except: без указания
    конкретного исключения.

Давайте посмотрим, что flake8 скажет по поводу этого файла:

$ flake8 bad_code.py
bad_code.py:1:1: F403 'from math import *' used; unable to detect undefined names
bad_code.py:2:1: F401 'itertools' imported but unused
bad_code.py:4:1: E302 expected 2 blank lines, found 1
bad_code.py:4:4: E271 multiple spaces after keyword
bad_code.py:4:25: E211 whitespace before '('
bad_code.py:4:33: E202 whitespace before ')'
bad_code.py:5:1: W191 indentation contains tabs
bad_code.py:5:8: E271 multiple spaces after keyword
bad_code.py:5:10: F405 'sqrt' may be undefined, or defined from star imports: math
bad_code.py:5:21: E202 whitespace before ')'
bad_code.py:7:1: E302 expected 2 blank lines, found 1
bad_code.py:7:23: E741 ambiguous variable name 'l'
bad_code.py:8:1: E101 indentation contains mixed spaces and tabs
bad_code.py:9:1: E101 indentation contains mixed spaces and tabs
bad_code.py:11:1: E305 expected 2 blank lines after class or function definition, found 1
bad_code.py:12:1: E101 indentation contains mixed spaces and tabs
bad_code.py:13:1: E101 indentation contains mixed spaces and tabs
bad_code.py:13:20: E225 missing whitespace around operator
bad_code.py:14:1: E101 indentation contains mixed spaces and tabs
bad_code.py:14:67: W291 trailing whitespace
bad_code.py:15:1: E101 indentation contains mixed spaces and tabs
bad_code.py:15:14: W291 trailing whitespace
bad_code.py:16:1: E101 indentation contains mixed spaces and tabs
bad_code.py:16:5: E722 do not use bare 'except'
bad_code.py:17:1: E101 indentation contains mixed spaces and tabs

Как видите, flake8 нашёл кучу ошибок. Для каждой ошибки указана строка
и номер символа в строке (не всегда точный), где произошла ошибка.
Также у каждой категории ошибок есть свой код: E101, W291 и т.д.
Эти коды ошибок могут использоваться для включения/отключения правил.
Тем не менее, не все ошибки были найдены. Давайте установим пару плагинов,
чтобы добавить ещё правил!

Плагины

Как я уже говорил, для flake8 написано множество плагинов.
Обычно плагины легко гуглятся или находятся в списках плагинов.
Есть плагины для всех популярных фреймворков и библиотек — пользуйтесь ими!
Давайте для нашего простого примера установим
flake8-bugbear
(находит распространённые логические ошибки) и
pep8-naming
(проверяет имена на соответствие PEP8).

Плагины устанавливаются так же, как и сам flake8 (для краткости я
не буду писать примеры для pipenv и poetry — сами сможете обобщить):

$ pip install flake8-bugbear pep8-naming

Давайте убедимся, что плагины действительно установились
и flake8 может их найти:

$ flake8 --version
3.8.1 (flake8-bugbear: 20.1.4, mccabe: 0.6.1, naming: 0.10.0, pycodestyle: 2.6.0, pyflakes: 2.2.0) CPython 3.8.2 on Linux

Если вы видите в списке в скобках названия ваших плагинов, то всё хорошо.

Теперь снова проверим наш файл:

$ flake8 bad_code.py
bad_code.py:1:1: F403 'from math import *' used; unable to detect undefined names
bad_code.py:2:1: F401 'itertools' imported but unused
bad_code.py:4:1: E302 expected 2 blank lines, found 1
bad_code.py:4:4: E271 multiple spaces after keyword
bad_code.py:4:6: N802 function name 'CalculateSquareRoot' should be lowercase
bad_code.py:4:25: E211 whitespace before '('
bad_code.py:4:28: N803 argument name 'Number' should be lowercase
bad_code.py:4:33: E202 whitespace before ')'
bad_code.py:5:1: W191 indentation contains tabs
bad_code.py:5:8: E271 multiple spaces after keyword
bad_code.py:5:10: F405 'sqrt' may be undefined, or defined from star imports: math
bad_code.py:5:21: E202 whitespace before ')'
bad_code.py:7:1: E302 expected 2 blank lines, found 1
bad_code.py:7:23: E741 ambiguous variable name 'l'
bad_code.py:7:25: B006 Do not use mutable data structures for argument defaults.  They are created during function definition time. All calls to the function reuse this one instance of that data structure, persisting changes between them.
bad_code.py:8:1: E101 indentation contains mixed spaces and tabs
bad_code.py:9:1: E101 indentation contains mixed spaces and tabs
bad_code.py:11:1: E305 expected 2 blank lines after class or function definition, found 1
bad_code.py:12:1: E101 indentation contains mixed spaces and tabs
bad_code.py:13:1: E101 indentation contains mixed spaces and tabs
bad_code.py:13:20: E225 missing whitespace around operator
bad_code.py:14:1: E101 indentation contains mixed spaces and tabs
bad_code.py:14:67: W291 trailing whitespace
bad_code.py:15:1: E101 indentation contains mixed spaces and tabs
bad_code.py:15:14: W291 trailing whitespace
bad_code.py:16:1: E101 indentation contains mixed spaces and tabs
bad_code.py:16:5: E722 do not use bare 'except'
bad_code.py:16:5: B001 Do not use bare `except:`, it also catches unexpected events like memory errors, interrupts, system exit, and so on.  Prefer `except Exception:`.  If you're sure what you're doing, be explicit and write `except BaseException:`.
bad_code.py:17:1: E101 indentation contains mixed spaces and tabs

В выводе появились новые категории ошибок (N802, B006)
— они как раз добавлены плагинами. На этот раз, как мне кажется,
найдены все ошибки. К сожалению, flake8 не умеет сам чинить
найденные ошибки, поэтому давайте сделаем это вручную:

Обратите внимание на строки 8 и 10, там содержится комментарии # noqa.
При помощи этих комментариев можно заставить flake8 игнорировать ошибки.
Это бывает полезно, когда по какой-то причине код должен остаться именно
таким, например:

  • он автоматически сгенерирован и исправление в нём ошибок не имеет смысла;
  • исправление этой ошибки породит куда более уродливый код,
    чем комментарий # noqa;
  • у вас просто сейчас нет времени, чтобы исправлять эту ошибку
    (плохая отмазка, серьёзно).

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

Конфигурация

flake8 для работы не требует никакой конфигурации.
Он имеет достаточно (но не слишком) строгие настройки по умолчанию,
которые подойдут большинству пользователей, но иногда бывает нужно
отключить (или наоборот включить) определённые правила на уровне всего проекта.
Сделать это можно через файлы .flake8 или setup.cfg в корне проекта.
Если у вас в проекте уже есть файл setup.cfg, то можно добавить конфигурацию
flake8 в него. Если вы предпочитаете для каждой утилиты держать
отдельный файл конфигурации, то используйте .flake8. В любом случае,
формат для обоих этих файлов совпадает:

[flake8]
ignore = D203,E741
exclude =
    # No need to traverse our git directory
    .git,
    # There's no value in checking cache directories
    __pycache__,
    # The conf file is mostly autogenerated, ignore it
    docs/source/conf.py,
    # The old directory contains Flake8 2.0
    old,
    # This contains our built documentation
    build,
    # This contains builds of flake8 that we don't want to check
    dist
max-complexity = 10

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

Если же вам не хватает какого-нибудь правила, и его нет даже в уже
готовых плагинах, то написание собственного плагина
— не такая уж и сложная задача.
Я попробовал,
у меня на это ушло 2-3 часа.

pylint

pylint — это ещё один популярный линтер для Python.
Этот линтер значительно умнее и продвинутее flake8.
В pylint из коробки заложено очень много правил и рекомендаций,
и по умолчанию они все включены, так что он достаточно строгий и придирчивый.
Чтобы интегрировать его в существующий большой проект придётся потратить
некоторое время, чтобы выбрать те правила, которые для вас важны.
Так же как и flake8, pylint поддерживает плагины для расширения
базовой функциональности, но насколько я вижу, экосистема плагинов у pylint
значительно беднее.

Также при каждом запуске pylint выводит оценку качества кода
по десятибалльной шкале, а также следит, как эта оценка меняется
с течением времени. Достичь десятки очень сложно, но это благородная цель,
к которой нужно стремиться.

Установка

Установка pylint принципиально ничем не отличается от установки flake8.
Выполнить внутри виртуального окружения проекта:

Для pipenv:

$ pipenv install --dev pylint

Для poetry:

$ poetry add --dev pylint

Использование

pylint можно натравить на определённый файл:

С директориями у pylint дела обстоят чуть сложнее. Все директории он
обрабатывает как питоновские модули, поэтому если в директории нет хотя бы
пустого файла __init__.py, то работать с ней pylint не сможет. Имейте
это ввиду.

Давайте попросим pylint прокомментировать файл с плохими практиками
из предыдущего примера:

$ pylint bad_code.py
************* Module bad_code
bad_code.py:4:25: C0326: No space allowed before bracket
def  CalculateSquareRoot (Number ):
                         ^ (bad-whitespace)
bad_code.py:4:33: C0326: No space allowed before bracket
def  CalculateSquareRoot (Number ):
                                 ^ (bad-whitespace)
bad_code.py:5:0: W0312: Found indentation with tabs instead of spaces (mixed-indentation)
bad_code.py:5:21: C0326: No space allowed before bracket
    return  sqrt(Number )
                     ^ (bad-whitespace)
bad_code.py:13:19: C0326: Exactly one space required around assignment
        your_number=float(input('Enter your number: '))
                   ^ (bad-whitespace)
bad_code.py:14:66: C0303: Trailing whitespace (trailing-whitespace)
bad_code.py:15:13: C0303: Trailing whitespace (trailing-whitespace)
bad_code.py:1:0: W0622: Redefining built-in 'pow' (redefined-builtin)
bad_code.py:1:0: C0114: Missing module docstring (missing-module-docstring)
bad_code.py:1:0: W0401: Wildcard import math (wildcard-import)
bad_code.py:4:0: C0103: Function name "CalculateSquareRoot" doesn't conform to snake_case naming style (invalid-name)
bad_code.py:4:0: C0103: Argument name "Number" doesn't conform to snake_case naming style (invalid-name)
bad_code.py:4:0: C0116: Missing function or method docstring (missing-function-docstring)
bad_code.py:7:0: W0102: Dangerous default value [] as argument (dangerous-default-value)
bad_code.py:7:0: C0103: Argument name "l" doesn't conform to snake_case naming style (invalid-name)
bad_code.py:7:0: C0116: Missing function or method docstring (missing-function-docstring)
bad_code.py:16:4: W0702: No exception type(s) specified (bare-except)
bad_code.py:1:0: W0614: Unused import acos from wildcard import (unused-wildcard-import)
bad_code.py:1:0: W0614: Unused import acosh from wildcard import (unused-wildcard-import)
bad_code.py:1:0: W0614: Unused import asin from wildcard import (unused-wildcard-import)
bad_code.py:1:0: W0614: Unused import asinh from wildcard import (unused-wildcard-import)
...
bad_code.py:2:0: W0611: Unused import itertools (unused-import)
-------------------------------------
Your code has been rated at -41.43/10

Я немного сократил вывод. Как видите, даже без плагинов pylint нашёл
все ожидаемые ошибки, и даже больше — например, он даже предлагает написать
документацию.

По каждой ошибке можно запросить более подробную справку, используя
название правила из конца строки с ошибкой или код:

$ pylint --help-msg=missing-docstring
$ pylint --help-msg=R0902

Вот какие ошибки pylint находит для файла, который с точки зрения flake8
не содержит никаких ошибок:

$ pylint not_so_bad_code.py 
************* Module not_so_bad_code
not_so_bad_code.py:1:0: C0114: Missing module docstring (missing-module-docstring)
not_so_bad_code.py:4:0: C0116: Missing function or method docstring (missing-function-docstring)
not_so_bad_code.py:8:0: C0103: Argument name "l" doesn't conform to snake_case naming style (invalid-name)
not_so_bad_code.py:8:0: C0116: Missing function or method docstring (missing-function-docstring)
not_so_bad_code.py:20:11: W0703: Catching too general exception Exception (broad-except)
-----------------------------------
Your code has been rated at 6.67/10

А вот так в pylint можно игнорировать отдельную ошибку на строке прямо в файлах
с кодом:

def append_item(item, l=None):  # pylint: disable=C0103
   ...

Ещё pylint умеет игнорировать ошибки в блоках кода:

def test():
    # Disable all the no-member violations in this function
    # pylint: disable=no-member
    ...

И для файлов целиком. Вот так можно отключить все ошибки из категорий
Warning, Convention и Refactor:

А можно не проверять файл вообще:

Подробнее о правилах управления сообщениями
смотрите в документации.
Для более сложной настройки правил, придётся по-настоящему сконфигурировать
pylint.

Конфигурация

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

$ pylint --generate-rcfile > .pylintrc

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

Плагины

Давайте установим какой-нибудь популярный плагин, например,
pylint-django:

$ pip install pylint-django

Теперь запускать pylint нужно вот так:

$ pylint --load-plugins pylint_django [..other options..] <path_to_your_sources>

либо в .pylintrc нужно исправить директиву load-plugins:

load-plugins=pylint_django

Интеграция линтера в проект

Интегрировать линтер в проект можно на трёх уровнях.
Я рекомендую по возможности использовать все три, но обязательным
является как минимум один (лучше всего, чтобы это была CI система).

Редактор кода или IDE

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

PyCharm автоматически находить установленные flake8 и pylint внутри
интерпретатора проекта
и подключается к ним.

VS Code требует небольшой настройки, которая
описана здесь.

Git-хуки

Также читайте пост про Git-хуки и pre-commit.

В git есть возможность запрограммировать
определенные скрипты (хуки) в ответ на действия пользователя.
Например, можно запускать
какие-нибудь проверки перед коммитом, заново скачивать зависимости проекта
при переключении веток, высылать сообщение в рабочий чат
после пуша в удалённый репозиторий и вообще что угодно.

я запушель

Нас интересует возможность запускать линтер перед коммитом так,
чтобы если линтер найдёт какие-нибудь проблемы, операция коммита прерывалась.
Git-хуки можно настроить, написав несложный shell-скрипт,
но я рекомендую использовать для этого специальные утилиты,
такие как pre-commit.
Вот здесь
можно найти описание процесса настройки запуска flake8 через pre-commit.

Обратите внимание, что Git-хуки нужно будет настроить на машине каждого
разработчика в проекте.

Continuous Integration (CI)

Последний эшелоном защиты от попадания “сломанного” кода в основную ветку
репозитория является система непрерывной интеграции (CI) — такая, как:

  • GitHub Actions;
  • GitLab CI
    (а ещё читайте пост в блоге моего хорошего товарища про
    основы GitLab CI);
  • Travis CI;
  • или другая.

На каждый пуш в репозиторий система непрерывной интеграции должна
запускать проверки (включая все линтеры и тесты), и если что-то идёт
не так, рядом с коммитом должен появиться красный крестик.
Ветку с таким коммитом на конце нельзя будет слить с основной
веткой проекта через пулл-реквест на GitHub (или мёрдж-реквест на GitLab).
Пример того, как настроить GitHub Actions
для запуска flake8 и других питоновских проверок.

CI — это единственный надёжный способ обеспечить качество кода.
Предыдущие способы нужны скорее для удобства разработчика, чтобы он
как можно скорее получал обратную связь, но разработчик вправе проигнорировать
или отключить эти предупреждения.

Заключение

В подзаголовке этой статьи я написал фразу, что линтер способен
сэкономить разработчику один день жизни в месяц. Фраза может показаться
кликбейтной, но, поверьте мне, это так это и работает.
Возможно, я даже преуменьшил.
Чем раньше найдена ошибка, тем быстрее идёт разработка.
Иногда линтер предотвращает баги, иногда спасает от мучительного
траблшутинга. Линтеры абсолютно точно значительно сокращают время,
потраченное коллегами на код-ревью, потому что все тривиальные
ошибки будут отловлены автоматикой.

Не стоит недооценивать линтеры. Это те инструменты,
которые делают из “кодера” настоящего “software engineer”,
из мальчика — мужчину. Если вы до сих пор не пользуетесь каким-нибудь
линтером, то рекомендую всерьез задуматься над внедрением!

Я предпочитаю использовать flake8, потому что он простой
и понятный, как топор. С ним легко работать, его легко настроить
под свои нужды, а почти любые недостающие правила можно получить
через уже готовые плагины.

У pylint тоже есть свои последователи. Его ценят за подробный вывод
и большое количество правил в стандартной поставке.
Мне же pylint всегда казался слишком сложным в эксплуатации.

А кто-то вообще рекомендует устанавливать flake8 и pylint параллельно.

Если понравилась статья, то
подпишитесь на уведомления
о новых постах в блоге, чтобы ничего не пропустить!

Дополнительное чтение

  • документация flake8;
  • исходный код flake8;
  • список плагинов flake8;
  • сайт, где можно посмотреть правила flake8;
  • документация pylint;
  • исходный код pylint;
  • обсуждение “flake8 vs pylint” на Reddit;
  • пост на RealPython про качество кода;
  • статья на Хабре про линтеры.

Обложка: Sa Mu, Traffic Light

Linting highlights syntactical and stylistic problems in your Python source code, which often helps you identify and correct subtle programming errors or unconventional coding practices that can lead to errors. For example, linting detects use of an uninitialized or undefined variable, calls to undefined functions, missing parentheses, and even more subtle issues such as attempting to redefine built-in types or functions. Linting is thus distinct from Formatting because linting analyzes how the code runs and detects errors whereas formatting only restructures how code appears.

Note: Stylistic and syntactical code detection is enabled by the Language Server. To enable third-party linters for additional problem detection, you can enable them by using the Python: Select Linter command and selecting the appropriate linter.

Enable linting

To enable linters, open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and select the Python: Select Linter command. The Select Linter command adds "python.linting.<linter>Enabled": true to your settings, where <linter> is the name of the chosen linter. See Specific linters for details.

Enabling a linter prompts you to install the required packages in your selected environment for the chosen linter.

Prompt for installing a linter

Note: If you’re using a global environment and VS Code is not running elevated, linter installation may fail. In that case, either run VS Code elevated, or manually run the Python package manager to install the linter at an elevated command prompt for the same environment: for example sudo pip3 install pylint (macOS/Linux) or pip install pylint (Windows, at an elevated prompt).

Disable linting

You can easily toggle between enabling and disabling your linter. To switch, open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and select the Python: Enable/Disable Linting command.

This will populate a dropdown with the current linting state and options to Enable or Disable Python linting.

Python Enable Linting command dropdown

Run linting

To perform linting, open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), filter on «linting», and select Python: Run Linting. Linting will run automatically when you save a file.

Issues are shown in the Problems panel and as wavy underlines in the code editor. Hovering over an underlined issue displays the details:

Linting messages in the editor and the Problems panel

General linting settings

You can add any of the linting settings to your user settings.json file (opened with the File > Preferences > Settings command ⌘, (Windows, Linux Ctrl+,)). Refer to User and Workspace settings to find out more about working with settings in VS Code.

To change the linting behavior across all enabled linters, modify the following settings:

Feature Setting
(python.linting.)
Default value
Linting in general enabled true
Linting on file save lintOnSave true
Maximum number of linting messages maxNumberOfProblems 100
Exclude file and folder patterns ignorePatterns [".vscode/*.py", "**/site-packages/**/*.py"]

When enabling lintOnSave, you might also want to enable the generic files.autoSave option (see Save / Auto Save). The combination provides frequent linting feedback in your code as you type.

Specific linters

The following table provides a summary of available Python linters and their basic settings. For descriptions of individual settings, see the Linter settings reference.

Linter Package name for pip install command True/false enable setting
(python.linting.)
Arguments setting
(python.linting.)
Custom path setting
(python.linting.)
Pylint pylint pylintEnabled pylintArgs pylintPath
Flake8 flake8 flake8Enabled flake8Args flake8Path
mypy mypy mypyEnabled mypyArgs mypyPath
pycodestyle (pep8) pycodestyle pycodestyleEnabled pycodestyleArgs pycodestylePath
prospector prospector prospectorEnabled prospectorArgs prospectorPath
pylama pylama pylamaEnabled pylamaArgs pylamaPath
bandit bandit banditEnabled banditArgs banditPath

Note: If you don’t find your preferred linter in the table above, you can add support via an extension. The Python Extension Template makes it easy to integrate new Python tools into VS Code.

To select a different linter, use the Python: Select Linter command. You can also edit your settings manually to enable multiple linters. Note, that using the Select Linter command overwrites those edits.

Custom arguments are specified in the appropriate arguments setting for each linter. Each top-level element of an argument string that’s separated by a space on the command line must be a separate item in the args list. For example:

"python.linting.pylintArgs": ["--reports", "12", "--disable", "I0011"],
"python.linting.flake8Args": ["--ignore=E24,W504", "--verbose"]
"python.linting.pydocstyleArgs": ["--ignore=D400", "--ignore=D4"]

If a top-level element is a single value (delineated by quotation marks or braces), it still appears as a single item in the list even if the value itself contains spaces.

A custom path is generally unnecessary as the Python extension resolves the path to the linter based on the Python interpreter being used (see Environments). To use a different version of a linter, specify its path in the appropriate custom path setting. For example, if your selected interpreter is a virtual environment but you want to use a linter that’s installed in a global environment, then set the appropriate path setting to point to the global environment’s linter.

Note: The following sections provide additional details for the individual linters linked in the Specific linters table above. In general, custom rules must be specified in a separate file as required by the linter you’re using.

Pylint

Pylint messages fall into the categories in the following table with the indicated mapping to VS Code categories. You can change the setting to change the mapping.

Pylint category Description VS Code category mapping Applicable setting
(python.linting.)
Convention (C) Programming standard violation Information (underline) pylintCategorySeverity.convention
Refactor (R) Bad code smell Hint (light bulbs) pylintCategorySeverity.refactor
Warning (W) Python-specific problems Warning pylintCategorySeverity.warning
Error (E) Likely code bugs Error (underline) pylintCategorySeverity.error
Fatal (F) An error prevented further Pylint processing Error pylintCategorySeverity.fatal

Command-line arguments and configuration files

You can easily generate an options file using different methods. See Pylint command-line arguments for general switches.

If you’re using command-line arguments:

Command-line arguments can be used to load Pylint plugins, such as the plugin for Django:

"python.linting.pylintArgs": ["--load-plugins", "pylint_django"]

If you’re using a pylintrc file:

Options can also be specified in a pylintrc or .pylintrc options file in the workspace folder, as described on Pylint command line arguments.

To control which Pylint messages are shown, add the following contents to an options file:

[MESSAGES CONTROL]

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time.
#enable=

# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once).
#disable=

If you’re using Pylint:

You can create an options file using Pylint itself, by running the command below.

# Using an *nix shell or cmd on Windows
pylint --generate-rcfile > .pylintrc

If you are running Pylint in PowerShell, you have to explicitly specify a UTF-8 output encoding. This file contains sections for all the Pylint options, along with documentation in the comments.

pylint --generate-rcfile | Out-File -Encoding utf8 .pylintrc

pydocstyle

Command-line arguments and configuration files

See pydocstyle Command Line Interface for general options. For example, to ignore error D400 (first line should end with a period), add the following line to your settings.json file:

"python.linting.pydocstyleArgs": ["--ignore=D400"]

A code prefix also instructs pydocstyle to ignore specific categories of errors. For example, to ignore all Docstring Content issues (D4XXX errors), add the following line to settings.json:

"python.linting.pydocstyleArgs": ["--ignore=D4"]

More details can be found in the pydocstyle documentation.

Options can also be read from a [pydocstyle] section of any of the following configuration files:

  • setup.cfg
  • tox.ini
  • .pydocstyle
  • .pydocstyle.ini
  • .pydocstylerc
  • .pydocstylerc.ini

For more information, see Configuration Files.

Message category mapping

The Python extension maps all pydocstyle errors to the Convention (C) category.

pycodestyle (pep8)

Command-line arguments and configuration files

See pycodestyle example usage and output for general switches. For example, to ignore error E303 (too many blank lines), add the following line to your settings.json file:

"python.linting.pycodestyleArgs": ["--ignore=E303"]

pycodestyle options are read from the [pycodestyle] section of a tox.ini or setup.cfg file located in any parent folder of the path(s) being processed. For details, see pycodestyle configuration.

Message category mapping

The Python extension maps pycodestyle message categories to VS Code categories through the following settings. If desired, change the setting to change the mapping.

pycodestyle category Applicable setting
(python.linting.)
VS Code category mapping
W pycodestyleCategorySeverity.W Warning
E pycodestyleCategorySeverity.E Error

Prospector

Command-line arguments and configuration files

See Prospector Command Line Usage for general options. For example, to set a strictness level of «very high,» add the following line to your settings.json file:

"python.linting.prospectorArgs": ["-s", "veryhigh"]

It’s common with Prospector to use profiles to configure how Prospector runs. By default, Prospector loads the profile from a .prospector.yaml file in the current folder.

Because Prospector calls other tools, such as Pylint, any configuration files for those tools override tool-specific settings in .prospector.yaml. For example, suppose you specify the following, in .prospector.yaml:

pylint:
  disable:
    - too-many-arguments

If you also have a .pylintrc file that enables the too-many-arguments warning, you continue to see the warning from Pylint within VS Code.

Message category mapping

The Python extension maps all Prospector errors and warnings to the Error (E) category.

Flake8

Command-line arguments and configuration files

See Invoking Flake8 for general switches. For example, to ignore error E303 (too many blank lines), use the following setting:

"python.linting.flake8Args": ["--ignore=E303"]

By default, Flake8 ignores E121, E123, E126, E226, E24, and E704.

Flake8 user options are read from the C:Users<username>.flake8 (Windows) or ~/.config/flake8 (macOS/Linux) file.

At the project level, options are read from the [flake8] section of a tox.ini, setup.cfg, or .flake8 file.

For details, see Flake8 configuration.

Message category mapping

The Python extension maps flake8 message categories to VS Code categories through the following settings. If desired, change the setting to change the mapping.

Flake8 category Applicable setting
(python.linting.)
VS Code category mapping
F flake8CategorySeverity.F Error
E flake8CategorySeverity.E Error
W flake8CategorySeverity.W Warning

mypy

Message category mapping

The Python extension maps mypy message categories to VS Code categories through the following settings. If desired, change the setting to change the mapping.

mypy category Applicable setting
(python.linting.)
VS Code category mapping
error mypyCategorySeverity.error Error
note mypyCategorySeverity.note Information

Troubleshooting linting

Error message Cause Solution
… unable to import <module_name> The Python extension is using the wrong version of Pylint. Ensure that selected interpreter is a valid Python installation where Pylint is installed. Alternately, set the python.linting.pylintPath to an appropriate version of Pylint for the Python interpreter being used.
Linting with <linter> failed … The path to the Python interpreter is incorrect. Make sure you selected a valid interpreter path by running the Python: Select Interpreter command (see Environments).
The linter has not been installed in the current Python environment. Open a command prompt, navigate to the location where your selecter interpreter is, and run pip install for the linter.
The path to the linter is incorrect. Ensure that the appropriate python.linting.<linter>Path setting for the linter is correct.
Custom arguments are defined incorrectly. Check the appropriate python.linting.<linter>Args settings, and that the value of the setting is a list of the argument elements that are separated by spaces. For example, "python.linting.pylintPath": "pylint --load-plugins pylint_django" is incorrect. The correct syntax is "python.linting.pylintArgs": ["--load-plugins", "pylint_django"].

Next steps

  • Debugging — Learn to debug Python both locally and remotely.
  • Testing — Configure test environments and discover, run, and debug tests.
  • Basic Editing — Learn about the powerful VS Code editor.
  • Code Navigation — Move quickly through your source code.
  • Python Extension Template — Create an extension to integrate your favorite linter into VS Code.

4/30/2022

In this post , we will explore – How to Check Syntax Errors in Python Code.

You can use various options to check for any syntax errors in Python without executing the script .

Try the below options –


if( aicp_can_see_ads() ) {

}

Option 1 – Using Compilation Script :

  • Using Python basic compilation . Use the code below and save it as any .py file e.g pythonSyntaxChecker.py
import sys
your_python_script_name = sys.argv[1]
source = open(your_python_script_name, 'r').read() + 'n'
compile(source, your_python_script_name, 'exec')
  • Next run your Python script(say yourPythonScript.py) against the above script
python3 pythonSyntaxChecker.py yourPythonScript.py
OR
python pythonSyntaxChecker.py yourPythonScript.py

Option 2 – Using Direct Compilation :

  • You can directly compile your Python script
  • Note the below poinst –
    • python returns a non-zero exit code if the compilation fails.
    • Also type errors are not detected — those are only detected at runtime
python -m py_compile yourPythonScript.py

Option 3 – Using Pychecker :

  • You can use PyChecker to syntax check your python code. Use code below from the command line:
    pychecker [options] YOUR_PYTHON_SCRIPT.py
  • The [options] provides below features –
    • –only  –> only warn about files passed on the command line
    • -#, –limit –> the maximum number of warnings to be displayed
    • –no-shadowbuiltin –> check if a variable shadows a builtin
    • -q, –stdlib –> ignore warnings from files under standard library
    • -T, –argsused –> unused method/function arguments
  • If you want to syntax check multiple Python scripts at one go ,


if( aicp_can_see_ads() ) {

}

pychecker <YOUR_DIR>/*.py

Sample how pychecker shows the syntax errors –

script1.py:5: Imported module (string) not used
script1.py:6: Instantiating an object with arguments, but no constructor
script1.py:7: Object (useless) has no attribute (valeu)
script1.py:8: No local variable (var1)
script1.py:9: self is not first method argument

Option 4 – Using Pyflakes :

  • Another worthy option to try – https://github.com/PyCQA/pyflakes
pyflakes yourPythonScript.py

Option 5 – Using “ast” module

  • The ast module helps to process trees of the Python abstract syntax grammar – basically ast helps to find out the current grammar appearance.
  • More here – https://docs.python.org/3/library/ast.html
  • Using CLI
python -c "import ast; ast.parse(open('yourPythonScript.py').read())"
  • Check syntax of any block of code
import ast
tree = ast.parse("print ('This is Great')")
ast.dump(tree)
"Module(body=[Expr(value=Call(func=Name(id='print', ctx=Load()), args=[Str(s='This is Great')], keywords=[]))])"
  • Alternatively use as a python script
import ast, traceback

g = '<YOUR PYTHON SCRIPT NAME>'
with open(g) as f:
  source = f.read()
valid = True

try:
  ast.parse(source)

except SyntaxError:
  valid = False
  traceback.print_exc()

finally:
  print(valid)
  ast.dump(source)


if( aicp_can_see_ads() ) {

}

Hope this write up was helpful.

Other Interesting Reads –

  • How To Create A Kerberos Keytab File ?

  • How To Code a PySpark Cassandra Application ?

  • How To Setup Spark Scala SBT in Eclipse

  • What Are The Most Important Metrics to Monitor in Kafka ?

python syntax check, python syntax, invalid syntax python, python for loop syntax, python if syntax, python, pycharm, django, matplotlib, python online, python programming, python list, learn python, python syntax checker,How do I check Python syntax, How do I check Python syntax online, What is Python basic syntax, What Is syntax check,check python script online,python code tester,how to find error in python code ,pep8 checker,python 3.5 syntax checker,python syntax error,python check function,bug checker python, python syntax checker command line, python 3.5 syntax checker, python syntax error fixer,syntaxerror: invalid syntax python 3,invalid syntax python print,how to resolve name error in python,invalid syntax python def,pylint syntax error,how to find error in python code,file <stdin>”, line 1 syntaxerror: invalid syntax,online python compiler, python find syntax error,How to find syntax error in python,How to solve the python syntax error,What is a syntax error in python,How does Python handle syntax errors,python syntax error,how to find error in python code,python compiler invalid syntax python ,check python script online,python code tester,occurs when a syntax error is raised for a module


if( aicp_can_see_ads() ) {

}

Pylint checkers’ options and switches#

Pylint checkers can provide three set of features:

  • options that control their execution,

  • messages that they can raise,

  • reports that they can generate.

Below is a list of all checkers and their features.

Async checker#

Verbatim name of the checker is async.

Async checker Messages#

not-async-context-manager (E1701)

Async context manager ‘%s’ doesn’t implement __aenter__ and __aexit__.
Used when an async context manager is used with an object that does not
implement the async context management protocol. This message can’t be
emitted when using Python < 3.5.

yield-inside-async-function (E1700)

Yield inside async function
Used when an yield or yield from statement is found inside an async
function. This message can’t be emitted when using Python < 3.5.

Basic checker#

Verbatim name of the checker is basic.

See also basic checker’s options’ documentation

Basic checker Messages#

not-in-loop (E0103)

%r not properly in loop
Used when break or continue keywords are used outside a loop.

function-redefined (E0102)

%s already defined line %s
Used when a function / class / method is redefined.

continue-in-finally (E0116)

‘continue’ not supported inside ‘finally’ clause
Emitted when the continue keyword is found inside a finally clause, which
is a SyntaxError.

abstract-class-instantiated (E0110)

Abstract class %r with abstract methods instantiated
Used when an abstract class with abc.ABCMeta as metaclass has abstract
methods and is instantiated.

star-needs-assignment-target (E0114)

Can use starred expression only in assignment target
Emitted when a star expression is not used in an assignment target.

duplicate-argument-name (E0108)

Duplicate argument name %s in function definition
Duplicate argument names in function definitions are syntax errors.

return-in-init (E0101)

Explicit return in __init__
Used when the special class method __init__ has an explicit return value.

too-many-star-expressions (E0112)

More than one starred expression in assignment
Emitted when there are more than one starred expressions (*x) in an
assignment. This is a SyntaxError.

nonlocal-and-global (E0115)

Name %r is nonlocal and global
Emitted when a name is both nonlocal and global.

used-prior-global-declaration (E0118)

Name %r is used prior to global declaration
Emitted when a name is used prior a global declaration, which results in an
error since Python 3.6. This message can’t be emitted when using Python <
3.6.

return-outside-function (E0104)

Return outside function
Used when a «return» statement is found outside a function or method.

return-arg-in-generator (E0106)

Return with argument inside generator
Used when a «return» statement with an argument is found outside in a
generator function or method (e.g. with some «yield» statements). This
message can’t be emitted when using Python >= 3.3.

invalid-star-assignment-target (E0113)

Starred assignment target must be in a list or tuple
Emitted when a star expression is used as a starred assignment target.

bad-reversed-sequence (E0111)

The first reversed() argument is not a sequence
Used when the first argument to reversed() builtin isn’t a sequence (does not
implement __reversed__, nor __getitem__ and __len__

nonexistent-operator (E0107)

Use of the non-existent %s operator
Used when you attempt to use the C-style pre-increment or pre-decrement
operator — and ++, which doesn’t exist in Python.

yield-outside-function (E0105)

Yield outside function
Used when a «yield» statement is found outside a function or method.

init-is-generator (E0100)

__init__ method is a generator
Used when the special class method __init__ is turned into a generator by a
yield in its body.

misplaced-format-function (E0119)

format function is not called on str
Emitted when format function is not called on str object. e.g doing
print(«value: {}»).format(123) instead of print(«value: {}».format(123)).
This might not be what the user intended to do.

nonlocal-without-binding (E0117)

nonlocal name %s found without binding
Emitted when a nonlocal variable does not have an attached name somewhere in
the parent scopes

lost-exception (W0150)

%s statement in finally block may swallow exception
Used when a break or a return statement is found inside the finally clause of
a try…finally block: the exceptions raised in the try clause will be
silently swallowed instead of being re-raised.

assert-on-tuple (W0199)

Assert called on a populated tuple. Did you mean ‘assert x,y’?
A call of assert on a tuple will always evaluate to true if the tuple is not
empty, and will always evaluate to false if it is.

assert-on-string-literal (W0129)

Assert statement has a string literal as its first argument. The assert will %s fail.
Used when an assert statement has a string literal as its first argument,
which will cause the assert to always pass.

self-assigning-variable (W0127)

Assigning the same variable %r to itself
Emitted when we detect that a variable is assigned to itself

comparison-with-callable (W0143)

Comparing against a callable, did you omit the parenthesis?
This message is emitted when pylint detects that a comparison with a callable
was made, which might suggest that some parenthesis were omitted, resulting
in potential unwanted behaviour.

nan-comparison (W0177)

Comparison %s should be %s
Used when an expression is compared to NaN values like numpy.NaN and
float(‘nan’).

dangerous-default-value (W0102)

Dangerous default value %s as argument
Used when a mutable value as list or dictionary is detected in a default
value for an argument.

duplicate-key (W0109)

Duplicate key %r in dictionary
Used when a dictionary expression binds the same key multiple times.

duplicate-value (W0130)

Duplicate value %r in set
This message is emitted when a set contains the same value two or more times.

useless-else-on-loop (W0120)

Else clause on loop without a break statement, remove the else and de-indent all the code inside it
Loops should only have an else clause if they can exit early with a break
statement, otherwise the statements under else should be on the same scope as
the loop itself.

pointless-exception-statement (W0133)

Exception statement has no effect
Used when an exception is created without being assigned, raised or returned
for subsequent use elsewhere.

expression-not-assigned (W0106)

Expression «%s» is assigned to nothing
Used when an expression that is not a function call is assigned to nothing.
Probably something else was intended.

confusing-with-statement (W0124)

Following «as» with another context manager looks like a tuple.
Emitted when a with statement component returns multiple values and uses
name binding with as only for a part of those values, as in with ctx() as
a, b. This can be misleading, since it’s not clear if the context manager
returns a tuple or if the node without a name binding is another context
manager.

unnecessary-lambda (W0108)

Lambda may not be necessary
Used when the body of a lambda expression is a function call on the same
argument list as the lambda itself; such lambda expressions are in all but a
few cases replaceable with the function being called in the body of the
lambda.

named-expr-without-context (W0131)

Named expression used without context
Emitted if named expression is used to do a regular assignment outside a
context like if, for, while, or a comprehension.

redeclared-assigned-name (W0128)

Redeclared variable %r in assignment
Emitted when we detect that a variable was redeclared in the same assignment.

pointless-statement (W0104)

Statement seems to have no effect
Used when a statement doesn’t have (or at least seems to) any effect.

pointless-string-statement (W0105)

String statement has no effect
Used when a string is used as a statement (which of course has no effect).
This is a particular case of W0104 with its own message so you can easily
disable it if you’re using those strings as documentation, instead of
comments.

unnecessary-pass (W0107)

Unnecessary pass statement
Used when a «pass» statement that can be avoided is encountered.

unreachable (W0101)

Unreachable code
Used when there is some code behind a «return» or «raise» statement, which
will never be accessed.

eval-used (W0123)

Use of eval
Used when you use the «eval» function, to discourage its usage. Consider
using ast.literal_eval for safely evaluating strings containing Python
expressions from untrusted sources.

exec-used (W0122)

Use of exec
Raised when the ‘exec’ statement is used. It’s dangerous to use this function
for a user input, and it’s also slower than actual code in general. This
doesn’t mean you should never use it, but you should consider alternatives
first and restrict the functions available.

using-constant-test (W0125)

Using a conditional statement with a constant value
Emitted when a conditional statement (If or ternary if) uses a constant value
for its test. This might not be what the user intended to do.

missing-parentheses-for-call-in-test (W0126)

Using a conditional statement with potentially wrong function or method call due to missing parentheses
Emitted when a conditional statement (If or ternary if) seems to wrongly call
a function due to missing parentheses

comparison-of-constants (R0133)

Comparison between constants: ‘%s %s %s’ has a constant value
When two literals are compared with each other the result is a constant.
Using the constant directly is both easier to read and more performant.
Initializing ‘True’ and ‘False’ this way is not required since Python 2.3.

literal-comparison (R0123)

In ‘%s’, use ‘%s’ when comparing constant literals not ‘%s’ (‘%s’)
Used when comparing an object to a literal, which is usually what you do not
want to do, since you can compare to a different literal than what was
expected altogether.

comparison-with-itself (R0124)

Redundant comparison — %s
Used when something is compared against itself.

invalid-name (C0103)

%s name «%s» doesn’t conform to %s
Used when the name doesn’t conform to naming rules associated to its type
(constant, variable, class…).

singleton-comparison (C0121)

Comparison %s should be %s
Used when an expression is compared to singleton values like True, False or
None.

disallowed-name (C0104)

Disallowed name «%s»
Used when the name matches bad-names or bad-names-rgxs- (unauthorized names).

empty-docstring (C0112)

Empty %s docstring
Used when a module, function, class or method has an empty docstring (it
would be too easy ;).

missing-class-docstring (C0115)

Missing class docstring
Used when a class has no docstring. Even an empty class must have a
docstring.

missing-function-docstring (C0116)

Missing function or method docstring
Used when a function or method has no docstring. Some special methods like
__init__ do not require a docstring.

missing-module-docstring (C0114)

Missing module docstring
Used when a module has no docstring. Empty modules do not require a
docstring.

typevar-name-incorrect-variance (C0105)

Type variable name does not reflect variance%s
Emitted when a TypeVar name doesn’t reflect its type variance. According to
PEP8, it is recommended to add suffixes ‘_co’ and ‘_contra’ to the variables
used to declare covariant or contravariant behaviour respectively. Invariant
(default) variables do not require a suffix. The message is also emitted when
invariant variables do have a suffix.

typevar-double-variance (C0131)

TypeVar cannot be both covariant and contravariant
Emitted when both the «covariant» and «contravariant» keyword arguments are
set to «True» in a TypeVar.

typevar-name-mismatch (C0132)

TypeVar name «%s» does not match assigned variable name «%s»
Emitted when a TypeVar is assigned to a variable that does not match its name
argument.

unidiomatic-typecheck (C0123)

Use isinstance() rather than type() for a typecheck.
The idiomatic way to perform an explicit typecheck in Python is to use
isinstance(x, Y) rather than type(x) == Y, type(x) is Y. Though there are
unusual situations where these give different results.

Basic checker Reports#

RP0101

Statistics by type

Classes checker#

Verbatim name of the checker is classes.

See also classes checker’s options’ documentation

Classes checker Messages#

access-member-before-definition (E0203)

Access to member %r before its definition line %s
Used when an instance member is accessed before it’s actually assigned.

method-hidden (E0202)

An attribute defined in %s line %s hides this method
Used when a class defines a method which is hidden by an instance attribute
from an ancestor class or set by some client code.

assigning-non-slot (E0237)

Assigning to attribute %r not defined in class slots
Used when assigning to an attribute not defined in the class slots.

duplicate-bases (E0241)

Duplicate bases for class %r
Duplicate use of base classes in derived classes raise TypeErrors.

invalid-enum-extension (E0244)

Extending inherited Enum class «%s»
Used when a class tries to extend an inherited Enum class. Doing so will
raise a TypeError at runtime.

inconsistent-mro (E0240)

Inconsistent method resolution order for class %r
Used when a class has an inconsistent method resolution order.

inherit-non-class (E0239)

Inheriting %r, which is not a class.
Used when a class inherits from something which is not a class.

invalid-slots (E0238)

Invalid __slots__ object
Used when an invalid __slots__ is found in class. Only a string, an iterable
or a sequence is permitted.

invalid-class-object (E0243)

Invalid assignment to ‘__class__’. Should be a class definition but got a ‘%s’
Used when an invalid object is assigned to a __class__ property. Only a class
is permitted.

invalid-slots-object (E0236)

Invalid object %r in __slots__, must contain only non empty strings
Used when an invalid (non-string) object occurs in __slots__.

no-method-argument (E0211)

Method %r has no argument
Used when a method which should have the bound instance as first argument has
no argument defined.

no-self-argument (E0213)

Method %r should have «self» as first argument
Used when a method has an attribute different the «self» as first argument.
This is considered as an error since this is a so common convention that you
shouldn’t break it!

unexpected-special-method-signature (E0302)

The special method %r expects %s param(s), %d %s given
Emitted when a special method was defined with an invalid number of
parameters. If it has too few or too many, it might not work at all.

class-variable-slots-conflict (E0242)

Value %r in slots conflicts with class variable
Used when a value in __slots__ conflicts with a class variable, property or
method.

invalid-bool-returned (E0304)

__bool__ does not return bool
Used when a __bool__ method returns something which is not a bool

invalid-bytes-returned (E0308)

__bytes__ does not return bytes
Used when a __bytes__ method returns something which is not bytes

invalid-format-returned (E0311)

__format__ does not return str
Used when a __format__ method returns something which is not a string

invalid-getnewargs-returned (E0312)

__getnewargs__ does not return a tuple
Used when a __getnewargs__ method returns something which is not a tuple

invalid-getnewargs-ex-returned (E0313)

__getnewargs_ex__ does not return a tuple containing (tuple, dict)
Used when a __getnewargs_ex__ method returns something which is not of the
form tuple(tuple, dict)

invalid-hash-returned (E0309)

__hash__ does not return int
Used when a __hash__ method returns something which is not an integer

invalid-index-returned (E0305)

__index__ does not return int
Used when an __index__ method returns something which is not an integer

non-iterator-returned (E0301)

__iter__ returns non-iterator
Used when an __iter__ method returns something which is not an iterable (i.e.
has no __next__ method)

invalid-length-returned (E0303)

__len__ does not return non-negative integer
Used when a __len__ method returns something which is not a non-negative
integer

invalid-length-hint-returned (E0310)

__length_hint__ does not return non-negative integer
Used when a __length_hint__ method returns something which is not a non-
negative integer

invalid-repr-returned (E0306)

__repr__ does not return str
Used when a __repr__ method returns something which is not a string

invalid-str-returned (E0307)

__str__ does not return str
Used when a __str__ method returns something which is not a string

arguments-differ (W0221)

%s %s %r method
Used when a method has a different number of arguments than in the
implemented interface or in an overridden method. Extra arguments with
default values are ignored.

arguments-renamed (W0237)

%s %s %r method
Used when a method parameter has a different name than in the implemented
interface or in an overridden method.

protected-access (W0212)

Access to a protected member %s of a client class
Used when a protected member (i.e. class member with a name beginning with an
underscore) is access outside the class or a descendant of the class where
it’s defined.

attribute-defined-outside-init (W0201)

Attribute %r defined outside __init__
Used when an instance attribute is defined outside the __init__ method.

subclassed-final-class (W0240)

Class %r is a subclass of a class decorated with typing.final: %r
Used when a class decorated with typing.final has been subclassed.

abstract-method (W0223)

Method %r is abstract in class %r but is not overridden in child class %r
Used when an abstract method (i.e. raise NotImplementedError) is not
overridden in concrete class.

overridden-final-method (W0239)

Method %r overrides a method decorated with typing.final which is defined in class %r
Used when a method decorated with typing.final has been overridden.

invalid-overridden-method (W0236)

Method %r was expected to be %r, found it instead as %r
Used when we detect that a method was overridden in a way that does not match
its base class which could result in potential bugs at runtime.

redefined-slots-in-subclass (W0244)

Redefined slots %r in subclass
Used when a slot is re-defined in a subclass.

signature-differs (W0222)

Signature differs from %s %r method
Used when a method signature is different than in the implemented interface
or in an overridden method.

bad-staticmethod-argument (W0211)

Static method with %r as first argument
Used when a static method has «self» or a value specified in valid-
classmethod-first-arg option or valid-metaclass-classmethod-first-arg option
as first argument.

super-without-brackets (W0245)

Super call without brackets
Used when a call to super does not have brackets and thus is not an actual
call and does not work as expected.

unused-private-member (W0238)

Unused private member `%s.%s`
Emitted when a private member of a class is defined but not used.

useless-parent-delegation (W0246)

Useless parent or super() delegation in method %r
Used whenever we can detect that an overridden method is useless, relying on
parent or super() delegation to do the same thing as another method from the
MRO.

non-parent-init-called (W0233)

__init__ method from a non direct base class %r is called
Used when an __init__ method is called on a class which is not in the direct
ancestors for the analysed class.

super-init-not-called (W0231)

__init__ method from base class %r is not called
Used when an ancestor class method has an __init__ method which is not called
by a derived class.

property-with-parameters (R0206)

Cannot have defined parameters for properties
Used when we detect that a property also has parameters, which are useless,
given that properties cannot be called with additional arguments.

useless-object-inheritance (R0205)

Class %r inherits from object, can be safely removed from bases in python3
Used when a class inherit from object, which under python3 is implicit, hence
can be safely removed from bases.

no-classmethod-decorator (R0202)

Consider using a decorator instead of calling classmethod
Used when a class method is defined without using the decorator syntax.

no-staticmethod-decorator (R0203)

Consider using a decorator instead of calling staticmethod
Used when a static method is defined without using the decorator syntax.

single-string-used-for-slots (C0205)

Class __slots__ should be a non-string iterable
Used when a class __slots__ is a simple string, rather than an iterable.

bad-classmethod-argument (C0202)

Class method %s should have %s as first argument
Used when a class method has a first argument named differently than the
value specified in valid-classmethod-first-arg option (default to «cls»),
recommended to easily differentiate them from regular instance methods.

bad-mcs-classmethod-argument (C0204)

Metaclass class method %s should have %s as first argument
Used when a metaclass class method has a first argument named differently
than the value specified in valid-metaclass-classmethod-first-arg option
(default to «mcs»), recommended to easily differentiate them from regular
instance methods.

bad-mcs-method-argument (C0203)

Metaclass method %s should have %s as first argument
Used when a metaclass method has a first argument named differently than the
value specified in valid-classmethod-first-arg option (default to «cls»),
recommended to easily differentiate them from regular instance methods.

method-check-failed (F0202)

Unable to check methods signature (%s / %s)
Used when Pylint has been unable to check methods signature compatibility for
an unexpected reason. Please report this kind if you don’t make sense of it.

Design checker#

Verbatim name of the checker is design.

See also design checker’s options’ documentation

Design checker Messages#

too-few-public-methods (R0903)

Too few public methods (%s/%s)
Used when class has too few public methods, so be sure it’s really worth it.

too-many-ancestors (R0901)

Too many ancestors (%s/%s)
Used when class has too many parent classes, try to reduce this to get a
simpler (and so easier to use) class.

too-many-arguments (R0913)

Too many arguments (%s/%s)
Used when a function or method takes too many arguments.

too-many-boolean-expressions (R0916)

Too many boolean expressions in if statement (%s/%s)
Used when an if statement contains too many boolean expressions.

too-many-branches (R0912)

Too many branches (%s/%s)
Used when a function or method has too many branches, making it hard to
follow.

too-many-instance-attributes (R0902)

Too many instance attributes (%s/%s)
Used when class has too many instance attributes, try to reduce this to get a
simpler (and so easier to use) class.

too-many-locals (R0914)

Too many local variables (%s/%s)
Used when a function or method has too many local variables.

too-many-public-methods (R0904)

Too many public methods (%s/%s)
Used when class has too many public methods, try to reduce this to get a
simpler (and so easier to use) class.

too-many-return-statements (R0911)

Too many return statements (%s/%s)
Used when a function or method has too many return statement, making it hard
to follow.

too-many-statements (R0915)

Too many statements (%s/%s)
Used when a function or method has too many statements. You should then split
it in smaller functions / methods.

Exceptions checker#

Verbatim name of the checker is exceptions.

See also exceptions checker’s options’ documentation

Exceptions checker Messages#

bad-except-order (E0701)

Bad except clauses order (%s)
Used when except clauses are not in the correct order (from the more specific
to the more generic). If you don’t fix the order, some exceptions may not be
caught by the most specific handler.

catching-non-exception (E0712)

Catching an exception which doesn’t inherit from Exception: %s
Used when a class which doesn’t inherit from Exception is used as an
exception in an except clause.

bad-exception-cause (E0705)

Exception cause set to something which is not an exception, nor None
Used when using the syntax «raise … from …», where the exception cause is
not an exception, nor None.

notimplemented-raised (E0711)

NotImplemented raised — should raise NotImplementedError
Used when NotImplemented is raised instead of NotImplementedError

raising-bad-type (E0702)

Raising %s while only classes or instances are allowed
Used when something which is neither a class nor an instance is raised (i.e.
a TypeError will be raised).

raising-non-exception (E0710)

Raising a new style class which doesn’t inherit from BaseException
Used when a new style class which doesn’t inherit from BaseException is
raised.

misplaced-bare-raise (E0704)

The raise statement is not inside an except clause
Used when a bare raise is not used inside an except clause. This generates an
error, since there are no active exceptions to be reraised. An exception to
this rule is represented by a bare raise inside a finally clause, which might
work, as long as an exception is raised inside the try block, but it is
nevertheless a code smell that must not be relied upon.

duplicate-except (W0705)

Catching previously caught exception type %s
Used when an except catches a type that was already caught by a previous
handler.

broad-exception-caught (W0718)

Catching too general exception %s
If you use a naked except Exception: clause, you might end up catching
exceptions other than the ones you expect to catch. This can hide bugs or
make it harder to debug programs when unrelated errors are hidden.

raise-missing-from (W0707)

Consider explicitly re-raising using %s’%s from %s’
Python’s exception chaining shows the traceback of the current exception, but
also of the original exception. When you raise a new exception after another
exception was caught it’s likely that the second exception is a friendly re-
wrapping of the first exception. In such cases raise from provides a better
link between the two tracebacks in the final error.

raising-format-tuple (W0715)

Exception arguments suggest string formatting might be intended
Used when passing multiple arguments to an exception constructor, the first
of them a string literal containing what appears to be placeholders intended
for formatting

binary-op-exception (W0711)

Exception to catch is the result of a binary «%s» operation
Used when the exception to catch is of the form «except A or B:». If
intending to catch multiple, rewrite as «except (A, B):»

wrong-exception-operation (W0716)

Invalid exception operation. %s
Used when an operation is done against an exception, but the operation is not
valid for the exception in question. Usually emitted when having binary
operations between exceptions in except handlers.

bare-except (W0702)

No exception type(s) specified
A bare except: clause will catch SystemExit and KeyboardInterrupt
exceptions, making it harder to interrupt a program with Control-C, and
can disguise other problems. If you want to catch all exceptions that signal
program errors, use except Exception: (bare except is equivalent to
except BaseException:).

broad-exception-raised (W0719)

Raising too general exception: %s
Raising exceptions that are too generic force you to catch exceptions
generically too. It will force you to use a naked except Exception:
clause. You might then end up catching exceptions other than the ones you
expect to catch. This can hide bugs or make it harder to debug programs when
unrelated errors are hidden.

try-except-raise (W0706)

The except handler raises immediately
Used when an except handler uses raise as its first or only operator. This is
useless because it raises back the exception immediately. Remove the raise
operator or the entire try-except-raise block!

Format checker#

Verbatim name of the checker is format.

See also format checker’s options’ documentation

Format checker Messages#

bad-indentation (W0311)

Bad indentation. Found %s %s, expected %s
Used when an unexpected number of indentation’s tabulations or spaces has
been found.

unnecessary-semicolon (W0301)

Unnecessary semicolon
Used when a statement is ended by a semi-colon («;»), which isn’t necessary
(that’s python, not C ;).

missing-final-newline (C0304)

Final newline missing
Used when the last line in a file is missing a newline.

line-too-long (C0301)

Line too long (%s/%s)
Used when a line is longer than a given number of characters.

mixed-line-endings (C0327)

Mixed line endings LF and CRLF
Used when there are mixed (LF and CRLF) newline signs in a file.

multiple-statements (C0321)

More than one statement on a single line
Used when more than on statement are found on the same line.

too-many-lines (C0302)

Too many lines in module (%s/%s)
Used when a module has too many lines, reducing its readability.

trailing-newlines (C0305)

Trailing newlines
Used when there are trailing blank lines in a file.

trailing-whitespace (C0303)

Trailing whitespace
Used when there is whitespace between the end of a line and the newline.

unexpected-line-ending-format (C0328)

Unexpected line ending format. There is ‘%s’ while it should be ‘%s’.
Used when there is different newline than expected.

superfluous-parens (C0325)

Unnecessary parens after %r keyword
Used when a single item in parentheses follows an if, for, or other keyword.

Imports checker#

Verbatim name of the checker is imports.

See also imports checker’s options’ documentation

Imports checker Messages#

relative-beyond-top-level (E0402)

Attempted relative import beyond top-level package
Used when a relative import tries to access too many levels in the current
package.

import-error (E0401)

Unable to import %s
Used when pylint has been unable to import a module.

deprecated-module (W4901)

Deprecated module %r
A module marked as deprecated is imported.

import-self (W0406)

Module import itself
Used when a module is importing itself.

preferred-module (W0407)

Prefer importing %r instead of %r
Used when a module imported has a preferred replacement module.

reimported (W0404)

Reimport %r (imported line %s)
Used when a module is imported more than once.

shadowed-import (W0416)

Shadowed %r (imported line %s)
Used when a module is aliased with a name that shadows another import.

wildcard-import (W0401)

Wildcard import %s
Used when from module import * is detected.

misplaced-future (W0410)

__future__ import is not the first non docstring statement
Python 2.5 and greater require __future__ import to be the first non
docstring statement in the module.

cyclic-import (R0401)

Cyclic import (%s)
Used when a cyclic import between two or more modules is detected.

consider-using-from-import (R0402)

Use ‘from %s import %s’ instead
Emitted when a submodule of a package is imported and aliased with the same
name, e.g., instead of import concurrent.futures as futures use from
concurrent import futures
.

wrong-import-order (C0411)

%s should be placed before %s
Used when PEP8 import order is not respected (standard imports first, then
third-party libraries, then local imports).

wrong-import-position (C0413)

Import «%s» should be placed at the top of the module
Used when code and imports are mixed.

useless-import-alias (C0414)

Import alias does not rename original package
Used when an import alias is same as original package, e.g., using import
numpy as numpy instead of import numpy as np.

import-outside-toplevel (C0415)

Import outside toplevel (%s)
Used when an import statement is used anywhere other than the module
toplevel. Move this import to the top of the file.

ungrouped-imports (C0412)

Imports from package %s are not grouped
Used when imports are not grouped by packages.

multiple-imports (C0410)

Multiple imports on one line (%s)
Used when import statement importing multiple modules is detected.

Imports checker Reports#

RP0401

External dependencies

RP0402

Modules dependencies graph

Lambda-Expressions checker#

Verbatim name of the checker is lambda-expressions.

Lambda-Expressions checker Messages#

unnecessary-lambda-assignment (C3001)

Lambda expression assigned to a variable. Define a function using the «def» keyword instead.
Used when a lambda expression is assigned to variable rather than defining a
standard function with the «def» keyword.

unnecessary-direct-lambda-call (C3002)

Lambda expression called directly. Execute the expression inline instead.
Used when a lambda expression is directly called rather than executing its
contents inline.

Logging checker#

Verbatim name of the checker is logging.

See also logging checker’s options’ documentation

Logging checker Messages#

logging-format-truncated (E1201)

Logging format string ends in middle of conversion specifier
Used when a logging statement format string terminates before the end of a
conversion specifier.

logging-too-few-args (E1206)

Not enough arguments for logging format string
Used when a logging format string is given too few arguments.

logging-too-many-args (E1205)

Too many arguments for logging format string
Used when a logging format string is given too many arguments.

logging-unsupported-format (E1200)

Unsupported logging format character %r (%#02x) at index %d
Used when an unsupported format character is used in a logging statement
format string.

logging-format-interpolation (W1202)

Use %s formatting in logging functions
Used when a logging statement has a call form of «logging.<logging
method>(format_string.format(format_args…))». Use another type of string
formatting instead. You can use % formatting but leave interpolation to the
logging function by passing the parameters as arguments. If logging-fstring-
interpolation is disabled then you can use fstring formatting. If logging-
not-lazy is disabled then you can use % formatting as normal.

logging-fstring-interpolation (W1203)

Use %s formatting in logging functions
Used when a logging statement has a call form of «logging.<logging
method>(f»…»)».Use another type of string formatting instead. You can use %
formatting but leave interpolation to the logging function by passing the
parameters as arguments. If logging-format-interpolation is disabled then you
can use str.format. If logging-not-lazy is disabled then you can use %
formatting as normal.

logging-not-lazy (W1201)

Use %s formatting in logging functions
Used when a logging statement has a call form of «logging.<logging
method>(format_string % (format_args…))». Use another type of string
formatting instead. You can use % formatting but leave interpolation to the
logging function by passing the parameters as arguments. If logging-fstring-
interpolation is disabled then you can use fstring formatting. If logging-
format-interpolation is disabled then you can use str.format.

Method Args checker#

Verbatim name of the checker is method_args.

See also method_args checker’s options’ documentation

Method Args checker Messages#

positional-only-arguments-expected (E3102)

`%s()` got some positional-only arguments passed as keyword arguments: %s
Emitted when positional-only arguments have been passed as keyword arguments.
Remove the keywords for the affected arguments in the function call. This
message can’t be emitted when using Python < 3.8.

missing-timeout (W3101)

Missing timeout argument for method ‘%s’ can cause your program to hang indefinitely
Used when a method needs a ‘timeout’ parameter in order to avoid waiting for
a long time. If no timeout is specified explicitly the default value is used.
For example for ‘requests’ the program will never time out (i.e. hang
indefinitely).

Metrics checker#

Verbatim name of the checker is metrics.

Metrics checker Reports#

RP0701

Raw metrics

Miscellaneous checker#

Verbatim name of the checker is miscellaneous.

See also miscellaneous checker’s options’ documentation

Miscellaneous checker Messages#

fixme (W0511)

Used when a warning note as FIXME or XXX is detected.

use-symbolic-message-instead (I0023)

Used when a message is enabled or disabled by id.

Modified Iteration checker#

Verbatim name of the checker is modified_iteration.

Modified Iteration checker Messages#

modified-iterating-dict (E4702)

Iterated dict ‘%s’ is being modified inside for loop body, iterate through a copy of it instead.
Emitted when items are added or removed to a dict being iterated through.
Doing so raises a RuntimeError.

modified-iterating-set (E4703)

Iterated set ‘%s’ is being modified inside for loop body, iterate through a copy of it instead.
Emitted when items are added or removed to a set being iterated through.
Doing so raises a RuntimeError.

modified-iterating-list (W4701)

Iterated list ‘%s’ is being modified inside for loop body, consider iterating through a copy of it instead.
Emitted when items are added or removed to a list being iterated through.
Doing so can result in unexpected behaviour, that is why it is preferred to
use a copy of the list.

Nested Min Max checker#

Verbatim name of the checker is nested_min_max.

Nested Min Max checker Messages#

nested-min-max (W3301)

Do not use nested call of ‘%s’; it’s possible to do ‘%s’ instead
Nested calls min(1, min(2, 3)) can be rewritten as min(1, 2, 3).

Newstyle checker#

Verbatim name of the checker is newstyle.

Newstyle checker Messages#

bad-super-call (E1003)

Bad first argument %r given to super()
Used when another argument than the current class is given as first argument
of the super builtin.

Nonascii-Checker checker#

Verbatim name of the checker is nonascii-checker.

Nonascii-Checker checker Messages#

non-ascii-file-name (W2402)

%s name «%s» contains a non-ASCII character. PEP 3131 only allows non-ascii identifiers, not file names.
Some editors don’t support non-ASCII file names properly. Even though Python
supports UTF-8 files since Python 3.5 this isn’t recommended for
interoperability. Further reading: —
https://peps.python.org/pep-0489/#export-hook-name —
https://peps.python.org/pep-0672/#confusing-features —
https://bugs.python.org/issue20485

non-ascii-name (C2401)

%s name «%s» contains a non-ASCII character, consider renaming it.
Used when the name contains at least one non-ASCII unicode character. See
https://peps.python.org/pep-0672/#confusing-features for a background why
this could be bad. If your programming guideline defines that you are
programming in English, then there should be no need for non ASCII characters
in Python Names. If not you can simply disable this check.

non-ascii-module-import (C2403)

%s name «%s» contains a non-ASCII character, use an ASCII-only alias for import.
Used when the name contains at least one non-ASCII unicode character. See
https://peps.python.org/pep-0672/#confusing-features for a background why
this could be bad. If your programming guideline defines that you are
programming in English, then there should be no need for non ASCII characters
in Python Names. If not you can simply disable this check.

Refactoring checker#

Verbatim name of the checker is refactoring.

See also refactoring checker’s options’ documentation

Refactoring checker Messages#

simplifiable-condition (R1726)

Boolean condition ‘%s’ may be simplified to ‘%s’
Emitted when a boolean condition is able to be simplified.

condition-evals-to-constant (R1727)

Boolean condition ‘%s’ will always evaluate to ‘%s’
Emitted when a boolean condition can be simplified to a constant value.

simplify-boolean-expression (R1709)

Boolean expression may be simplified to %s
Emitted when redundant pre-python 2.5 ternary syntax is used.

consider-using-in (R1714)

Consider merging these comparisons with ‘in’ by using ‘%s %sin (%s)’. Use a set instead if elements are hashable.
To check if a variable is equal to one of many values, combine the values
into a set or tuple and check if the variable is contained «in» it instead of
checking for equality against each of the values. This is faster and less
verbose.

consider-merging-isinstance (R1701)

Consider merging these isinstance calls to isinstance(%s, (%s))
Used when multiple consecutive isinstance calls can be merged into one.

use-dict-literal (R1735)

Consider using ‘%s’ instead of a call to ‘dict’.
Emitted when using dict() to create a dictionary instead of a literal ‘{ …
}’. The literal is faster as it avoids an additional function call.

consider-using-max-builtin (R1731)

Consider using ‘%s’ instead of unnecessary if block
Using the max builtin instead of a conditional improves readability and
conciseness.

consider-using-min-builtin (R1730)

Consider using ‘%s’ instead of unnecessary if block
Using the min builtin instead of a conditional improves readability and
conciseness.

consider-using-sys-exit (R1722)

Consider using ‘sys.exit’ instead
Contrary to ‘exit()’ or ‘quit()’, ‘sys.exit’ does not rely on the site module
being available (as the ‘sys’ module is always available).

consider-using-with (R1732)

Consider using ‘with’ for resource-allocating operations
Emitted if a resource-allocating assignment or call may be replaced by a
‘with’ block. By using ‘with’ the release of the allocated resources is
ensured even in the case of an exception.

super-with-arguments (R1725)

Consider using Python 3 style super() without arguments
Emitted when calling the super() builtin with the current class and instance.
On Python 3 these arguments are the default and they can be omitted.

use-list-literal (R1734)

Consider using [] instead of list()
Emitted when using list() to create an empty list instead of the literal [].
The literal is faster as it avoids an additional function call.

consider-using-dict-comprehension (R1717)

Consider using a dictionary comprehension
Emitted when we detect the creation of a dictionary using the dict() callable
and a transient list. Although there is nothing syntactically wrong with this
code, it is hard to read and can be simplified to a dict comprehension. Also
it is faster since you don’t need to create another transient list

consider-using-generator (R1728)

Consider using a generator instead ‘%s(%s)’
If your container can be large using a generator will bring better
performance.

consider-using-set-comprehension (R1718)

Consider using a set comprehension
Although there is nothing syntactically wrong with this code, it is hard to
read and can be simplified to a set comprehension. Also it is faster since
you don’t need to create another transient list

consider-using-get (R1715)

Consider using dict.get for getting values from a dict if a key is present or a default if not
Using the builtin dict.get for getting a value from a dictionary if a key is
present or a default if not, is simpler and considered more idiomatic,
although sometimes a bit slower

consider-using-join (R1713)

Consider using str.join(sequence) for concatenating strings from an iterable
Using str.join(sequence) is faster, uses less memory and increases
readability compared to for-loop iteration.

consider-using-ternary (R1706)

Consider using ternary (%s)
Used when one of known pre-python 2.5 ternary syntax is used.

consider-swap-variables (R1712)

Consider using tuple unpacking for swapping variables
You do not have to use a temporary variable in order to swap variables. Using
«tuple unpacking» to directly swap variables makes the intention more clear.

trailing-comma-tuple (R1707)

Disallow trailing comma tuple
In Python, a tuple is actually created by the comma symbol, not by the
parentheses. Unfortunately, one can actually create a tuple by misplacing a
trailing comma, which can lead to potential weird bugs in your code. You
should always use parentheses explicitly for creating a tuple.

stop-iteration-return (R1708)

Do not raise StopIteration in generator, use return statement instead
According to PEP479, the raise of StopIteration to end the loop of a
generator may lead to hard to find bugs. This PEP specify that raise
StopIteration has to be replaced by a simple return statement

inconsistent-return-statements (R1710)

Either all return statements in a function should return an expression, or none of them should.
According to PEP8, if any return statement returns an expression, any return
statements where no value is returned should explicitly state this as return
None, and an explicit return statement should be present at the end of the
function (if reachable)

redefined-argument-from-local (R1704)

Redefining argument with the local name %r
Used when a local name is redefining an argument, which might suggest a
potential error. This is taken in account only for a handful of name binding
operations, such as for iteration, with statement assignment and exception
handler assignment.

chained-comparison (R1716)

Simplify chained comparison between the operands
This message is emitted when pylint encounters boolean operation like «a < b
and b < c», suggesting instead to refactor it to «a < b < c»

simplifiable-if-expression (R1719)

The if expression can be replaced with %s
Used when an if expression can be replaced with ‘bool(test)’ or simply ‘test’
if the boolean cast is implicit.

simplifiable-if-statement (R1703)

The if statement can be replaced with %s
Used when an if statement can be replaced with ‘bool(test)’.

too-many-nested-blocks (R1702)

Too many nested blocks (%s/%s)
Used when a function or a method has too many nested blocks. This makes the
code less understandable and maintainable.

no-else-break (R1723)

Unnecessary «%s» after «break», %s
Used in order to highlight an unnecessary block of code following an if
containing a break statement. As such, it will warn when it encounters an
else following a chain of ifs, all of them containing a break statement.

no-else-continue (R1724)

Unnecessary «%s» after «continue», %s
Used in order to highlight an unnecessary block of code following an if
containing a continue statement. As such, it will warn when it encounters an
else following a chain of ifs, all of them containing a continue statement.

no-else-raise (R1720)

Unnecessary «%s» after «raise», %s
Used in order to highlight an unnecessary block of code following an if
containing a raise statement. As such, it will warn when it encounters an
else following a chain of ifs, all of them containing a raise statement.

no-else-return (R1705)

Unnecessary «%s» after «return», %s
Used in order to highlight an unnecessary block of code following an if
containing a return statement. As such, it will warn when it encounters an
else following a chain of ifs, all of them containing a return statement.

unnecessary-dict-index-lookup (R1733)

Unnecessary dictionary index lookup, use ‘%s’ instead
Emitted when iterating over the dictionary items (key-item pairs) and
accessing the value by index lookup. The value can be accessed directly
instead.

unnecessary-list-index-lookup (R1736)

Unnecessary list index lookup, use ‘%s’ instead
Emitted when iterating over an enumeration and accessing the value by index
lookup. The value can be accessed directly instead.

unnecessary-comprehension (R1721)

Unnecessary use of a comprehension, use %s instead.
Instead of using an identity comprehension, consider using the list, dict or
set constructor. It is faster and simpler.

use-a-generator (R1729)

Use a generator instead ‘%s(%s)’
Comprehension inside of ‘any’, ‘all’, ‘max’, ‘min’ or ‘sum’ is unnecessary. A
generator would be sufficient and faster.

useless-return (R1711)

Useless return at end of function or method
Emitted when a single «return» or «return None» statement is found at the end
of function or method definition. This statement can safely be removed
because Python will implicitly return None

use-implicit-booleaness-not-comparison (C1803)

‘%s’ can be simplified to ‘%s’ as an empty %s is falsey
Used when Pylint detects that collection literal comparison is being used to
check for emptiness; Use implicit booleaness instead of a collection classes;
empty collections are considered as false

unneeded-not (C0113)

Consider changing «%s» to «%s»
Used when a boolean expression contains an unneeded negation.

consider-iterating-dictionary (C0201)

Consider iterating the dictionary directly instead of calling .keys()
Emitted when the keys of a dictionary are iterated through the .keys()
method or when .keys() is used for a membership check. It is enough to
iterate through the dictionary itself, for key in dictionary. For
membership checks, if key in dictionary is faster.

consider-using-dict-items (C0206)

Consider iterating with .items()
Emitted when iterating over the keys of a dictionary and accessing the value
by index lookup. Both the key and value can be accessed by iterating using
the .items() method of the dictionary instead.

consider-using-enumerate (C0200)

Consider using enumerate instead of iterating with range and len
Emitted when code that iterates with range and len is encountered. Such code
can be simplified by using the enumerate builtin.

use-implicit-booleaness-not-len (C1802)

Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty
Used when Pylint detects that len(sequence) is being used without explicit
comparison inside a condition to determine if a sequence is empty. Instead of
coercing the length to a boolean, either rely on the fact that empty
sequences are false or compare the length against a scalar.

consider-using-f-string (C0209)

Formatting a regular string which could be a f-string
Used when we detect a string that is being formatted with format() or % which
could potentially be a f-string. The use of f-strings is preferred. Requires
Python 3.6 and py-version >= 3.6.

use-maxsplit-arg (C0207)

Use %s instead
Emitted when accessing only the first or last element of str.split(). The
first and last element can be accessed by using str.split(sep, maxsplit=1)[0]
or str.rsplit(sep, maxsplit=1)[-1] instead.

use-sequence-for-iteration (C0208)

Use a sequence type when iterating over values
When iterating over values, sequence types (e.g., lists, tuples,
ranges) are more efficient than sets.

Similarities checker#

Verbatim name of the checker is similarities.

See also similarities checker’s options’ documentation

Similarities checker Messages#

duplicate-code (R0801)

Similar lines in %s files
Indicates that a set of similar lines has been detected among multiple file.
This usually means that the code should be refactored to avoid this
duplication.

Similarities checker Reports#

RP0801

Duplication

Spelling checker#

Verbatim name of the checker is spelling.

See also spelling checker’s options’ documentation

Spelling checker Messages#

invalid-characters-in-docstring (C0403)

Invalid characters %r in a docstring
Used when a word in docstring cannot be checked by enchant.

wrong-spelling-in-comment (C0401)

Wrong spelling of a word ‘%s’ in a comment:
Used when a word in comment is not spelled correctly.

wrong-spelling-in-docstring (C0402)

Wrong spelling of a word ‘%s’ in a docstring:
Used when a word in docstring is not spelled correctly.

Stdlib checker#

Verbatim name of the checker is stdlib.

Stdlib checker Messages#

invalid-envvar-value (E1507)

%s does not support %s type argument
Env manipulation functions support only string type arguments. See
https://docs.python.org/3/library/os.html#os.getenv.

singledispatch-method (E1519)

singledispatch decorator should not be used with methods, use singledispatchmethod instead.
singledispatch should decorate functions and not class/instance methods. Use
singledispatchmethod for those cases.

singledispatchmethod-function (E1520)

singledispatchmethod decorator should not be used with functions, use singledispatch instead.
singledispatchmethod should decorate class/instance methods and not
functions. Use singledispatch for those cases.

bad-open-mode (W1501)

«%s» is not a valid mode for open.
Python supports: r, w, a[, x] modes with b, +, and U (only with r) options.
See https://docs.python.org/3/library/functions.html#open

invalid-envvar-default (W1508)

%s default type is %s. Expected str or None.
Env manipulation functions return None or str values. Supplying anything
different as a default may cause bugs. See
https://docs.python.org/3/library/os.html#os.getenv.

method-cache-max-size-none (W1518)

‘lru_cache(maxsize=None)’ or ‘cache’ will keep all method args alive indefinitely, including ‘self’
By decorating a method with lru_cache or cache the ‘self’ argument will be
linked to the function and therefore never garbage collected. Unless your
instance will never need to be garbage collected (singleton) it is
recommended to refactor code to avoid this pattern or add a maxsize to the
cache. The default value for maxsize is 128.

subprocess-run-check (W1510)

‘subprocess.run’ used without explicitly defining the value for ‘check’.
The check keyword is set to False by default. It means the process
launched by subprocess.run can exit with a non-zero exit code and fail
silently. It’s better to set it explicitly to make clear what the error-
handling behavior is.

forgotten-debug-statement (W1515)

Leaving functions creating breakpoints in production code is not recommended
Calls to breakpoint(), sys.breakpointhook() and pdb.set_trace() should be
removed from code that is not actively being debugged.

redundant-unittest-assert (W1503)

Redundant use of %s with constant value %r
The first argument of assertTrue and assertFalse is a condition. If a
constant is passed as parameter, that condition will be always true. In this
case a warning should be emitted.

shallow-copy-environ (W1507)

Using copy.copy(os.environ). Use os.environ.copy() instead.
os.environ is not a dict object but proxy object, so shallow copy has still
effects on original object. See https://bugs.python.org/issue15373 for
reference.

boolean-datetime (W1502)

Using datetime.time in a boolean context.
Using datetime.time in a boolean context can hide subtle bugs when the time
they represent matches midnight UTC. This behaviour was fixed in Python 3.5.
See https://bugs.python.org/issue13936 for reference. This message can’t be
emitted when using Python >= 3.5.

deprecated-argument (W4903)

Using deprecated argument %s of method %s()
The argument is marked as deprecated and will be removed in the future.

deprecated-class (W4904)

Using deprecated class %s of module %s
The class is marked as deprecated and will be removed in the future.

deprecated-decorator (W4905)

Using deprecated decorator %s()
The decorator is marked as deprecated and will be removed in the future.

deprecated-method (W4902)

Using deprecated method %s()
The method is marked as deprecated and will be removed in the future.

unspecified-encoding (W1514)

Using open without explicitly specifying an encoding
It is better to specify an encoding when opening documents. Using the system
default implicitly can create problems on other operating systems. See
https://peps.python.org/pep-0597/

subprocess-popen-preexec-fn (W1509)

Using preexec_fn keyword which may be unsafe in the presence of threads
The preexec_fn parameter is not safe to use in the presence of threads in
your application. The child process could deadlock before exec is called. If
you must use it, keep it trivial! Minimize the number of libraries you call
into. See https://docs.python.org/3/library/subprocess.html#popen-constructor

bad-thread-instantiation (W1506)

threading.Thread needs the target function
The warning is emitted when a threading.Thread class is instantiated without
the target function being passed as a kwarg or as a second argument. By
default, the first parameter is the group param, not the target param.

String checker#

Verbatim name of the checker is string.

See also string checker’s options’ documentation

String checker Messages#

bad-string-format-type (E1307)

Argument %r does not match format type %r
Used when a type required by format string is not suitable for actual
argument type

format-needs-mapping (E1303)

Expected mapping for format string, not %s
Used when a format string that uses named conversion specifiers is used with
an argument that is not a mapping.

truncated-format-string (E1301)

Format string ends in middle of conversion specifier
Used when a format string terminates before the end of a conversion
specifier.

missing-format-string-key (E1304)

Missing key %r in format string dictionary
Used when a format string that uses named conversion specifiers is used with
a dictionary that doesn’t contain all the keys required by the format string.

mixed-format-string (E1302)

Mixing named and unnamed conversion specifiers in format string
Used when a format string contains both named (e.g. ‘%(foo)d’) and unnamed
(e.g. ‘%d’) conversion specifiers. This is also used when a named conversion
specifier contains * for the minimum field width and/or precision.

too-few-format-args (E1306)

Not enough arguments for format string
Used when a format string that uses unnamed conversion specifiers is given
too few arguments

bad-str-strip-call (E1310)

Suspicious argument in %s.%s call
The argument to a str.{l,r,}strip call contains a duplicate character,

too-many-format-args (E1305)

Too many arguments for format string
Used when a format string that uses unnamed conversion specifiers is given
too many arguments.

bad-format-character (E1300)

Unsupported format character %r (%#02x) at index %d
Used when an unsupported format character is used in a format string.

anomalous-unicode-escape-in-string (W1402)

Anomalous Unicode escape in byte string: ‘%s’. String constant might be missing an r or u prefix.
Used when an escape like u is encountered in a byte string where it has no
effect.

anomalous-backslash-in-string (W1401)

Anomalous backslash in string: ‘%s’. String constant might be missing an r prefix.
Used when a backslash is in a literal string but not as an escape.

duplicate-string-formatting-argument (W1308)

Duplicate string formatting argument %r, consider passing as named argument
Used when we detect that a string formatting is repeating an argument instead
of using named string arguments

format-combined-specification (W1305)

Format string contains both automatic field numbering and manual field specification
Used when a PEP 3101 format string contains both automatic field numbering
(e.g. ‘{}’) and manual field specification (e.g. ‘{0}’).

bad-format-string-key (W1300)

Format string dictionary key should be a string, not %s
Used when a format string that uses named conversion specifiers is used with
a dictionary whose keys are not all strings.

implicit-str-concat (W1404)

Implicit string concatenation found in %s
String literals are implicitly concatenated in a literal iterable definition
: maybe a comma is missing ?

bad-format-string (W1302)

Invalid format string
Used when a PEP 3101 format string is invalid.

missing-format-attribute (W1306)

Missing format attribute %r in format specifier %r
Used when a PEP 3101 format string uses an attribute specifier ({0.length}),
but the argument passed for formatting doesn’t have that attribute.

missing-format-argument-key (W1303)

Missing keyword argument %r for format string
Used when a PEP 3101 format string that uses named fields doesn’t receive one
or more required keywords.

inconsistent-quotes (W1405)

Quote delimiter %s is inconsistent with the rest of the file
Quote delimiters are not used consistently throughout a module (with
allowances made for avoiding unnecessary escaping).

redundant-u-string-prefix (W1406)

The u prefix for strings is no longer necessary in Python >=3.0
Used when we detect a string with a u prefix. These prefixes were necessary
in Python 2 to indicate a string was Unicode, but since Python 3.0 strings
are Unicode by default.

unused-format-string-argument (W1304)

Unused format argument %r
Used when a PEP 3101 format string that uses named fields is used with an
argument that is not required by the format string.

unused-format-string-key (W1301)

Unused key %r in format string dictionary
Used when a format string that uses named conversion specifiers is used with
a dictionary that contains keys not required by the format string.

f-string-without-interpolation (W1309)

Using an f-string that does not have any interpolated variables
Used when we detect an f-string that does not use any interpolation
variables, in which case it can be either a normal string or a bug in the
code.

format-string-without-interpolation (W1310)

Using formatting for a string that does not have any interpolated variables
Used when we detect a string that does not have any interpolation variables,
in which case it can be either a normal string without formatting or a bug in
the code.

invalid-format-index (W1307)

Using invalid lookup key %r in format specifier %r
Used when a PEP 3101 format string uses a lookup specifier ({a[1]}), but the
argument passed for formatting doesn’t contain or doesn’t have that key as an
attribute.

Threading checker#

Verbatim name of the checker is threading.

Threading checker Messages#

useless-with-lock (W2101)

‘%s()’ directly created in ‘with’ has no effect
Used when a new lock instance is created by using with statement which has no
effect. Instead, an existing instance should be used to acquire lock.

Typecheck checker#

Verbatim name of the checker is typecheck.

See also typecheck checker’s options’ documentation

Typecheck checker Messages#

unsupported-assignment-operation (E1137)

%r does not support item assignment
Emitted when an object does not support item assignment (i.e. doesn’t define
__setitem__ method).

unsupported-delete-operation (E1138)

%r does not support item deletion
Emitted when an object does not support item deletion (i.e. doesn’t define
__delitem__ method).

invalid-unary-operand-type (E1130)

Emitted when a unary operand is used on an object which does not support this
type of operation.

unsupported-binary-operation (E1131)

Emitted when a binary arithmetic operation between two operands is not
supported.

no-member (E1101)

%s %r has no %r member%s
Used when a variable is accessed for a nonexistent member.

not-callable (E1102)

%s is not callable
Used when an object being called has been inferred to a non callable object.

unhashable-member (E1143)

‘%s’ is unhashable and can’t be used as a %s in a %s
Emitted when a dict key or set member is not hashable (i.e. doesn’t define
__hash__ method).

await-outside-async (E1142)

‘await’ should be used within an async function
Emitted when await is used outside an async function.

redundant-keyword-arg (E1124)

Argument %r passed by position and keyword in %s call
Used when a function call would result in assigning multiple values to a
function parameter, one value from a positional argument and one from a
keyword argument.

assignment-from-no-return (E1111)

Assigning result of a function call, where the function has no return
Used when an assignment is done on a function call but the inferred function
doesn’t return anything.

assignment-from-none (E1128)

Assigning result of a function call, where the function returns None
Used when an assignment is done on a function call but the inferred function
returns nothing but None.

not-context-manager (E1129)

Context manager ‘%s’ doesn’t implement __enter__ and __exit__.
Used when an instance in a with statement doesn’t implement the context
manager protocol(__enter__/__exit__).

repeated-keyword (E1132)

Got multiple values for keyword argument %r in function call
Emitted when a function call got multiple values for a keyword.

invalid-metaclass (E1139)

Invalid metaclass %r used
Emitted whenever we can detect that a class is using, as a metaclass,
something which might be invalid for using as a metaclass.

missing-kwoa (E1125)

Missing mandatory keyword argument %r in %s call
Used when a function call does not pass a mandatory keyword-only argument.

no-value-for-parameter (E1120)

No value for argument %s in %s call
Used when a function call passes too few arguments.

not-an-iterable (E1133)

Non-iterable value %s is used in an iterating context
Used when a non-iterable value is used in place where iterable is expected

not-a-mapping (E1134)

Non-mapping value %s is used in a mapping context
Used when a non-mapping value is used in place where mapping is expected

invalid-sequence-index (E1126)

Sequence index is not an int, slice, or instance with __index__
Used when a sequence type is indexed with an invalid type. Valid types are
ints, slices, and objects with an __index__ method.

invalid-slice-index (E1127)

Slice index is not an int, None, or instance with __index__
Used when a slice index is not an integer, None, or an object with an
__index__ method.

invalid-slice-step (E1144)

Slice step cannot be 0
Used when a slice step is 0 and the object doesn’t implement a custom
__getitem__ method.

too-many-function-args (E1121)

Too many positional arguments for %s call
Used when a function call passes too many positional arguments.

unexpected-keyword-arg (E1123)

Unexpected keyword argument %r in %s call
Used when a function call passes a keyword argument that doesn’t correspond
to one of the function’s parameter names.

dict-iter-missing-items (E1141)

Unpacking a dictionary in iteration without calling .items()
Emitted when trying to iterate through a dict without calling .items()

unsupported-membership-test (E1135)

Value ‘%s’ doesn’t support membership test
Emitted when an instance in membership test expression doesn’t implement
membership protocol (__contains__/__iter__/__getitem__).

unsubscriptable-object (E1136)

Value ‘%s’ is unsubscriptable
Emitted when a subscripted value doesn’t support subscription (i.e. doesn’t
define __getitem__ method or __class_getitem__ for a class).

keyword-arg-before-vararg (W1113)

Keyword argument before variable positional arguments list in the definition of %s function
When defining a keyword argument before variable positional arguments, one
can end up in having multiple values passed for the aforementioned parameter
in case the method is called with keyword arguments.

non-str-assignment-to-dunder-name (W1115)

Non-string value assigned to __name__
Emitted when a non-string value is assigned to __name__

arguments-out-of-order (W1114)

Positional arguments appear to be out of order
Emitted when the caller’s argument names fully match the parameter names in
the function signature but do not have the same order.

isinstance-second-argument-not-valid-type (W1116)

Second argument of isinstance is not a type
Emitted when the second argument of an isinstance call is not a type.

c-extension-no-member (I1101)

%s %r has no %r member%s, but source is unavailable. Consider adding this module to extension-pkg-allow-list if you want to perform analysis based on run-time introspection of living objects.
Used when a variable is accessed for non-existent member of C extension. Due
to unavailability of source static analysis is impossible, but it may be
performed by introspecting living objects in run-time.

Unicode Checker checker#

Verbatim name of the checker is unicode_checker.

Unicode Checker checker Messages#

bidirectional-unicode (E2502)

Contains control characters that can permit obfuscated code executed differently than displayed
bidirectional unicode are typically not displayed characters required to
display right-to-left (RTL) script (i.e. Chinese, Japanese, Arabic, Hebrew,
…) correctly. So can you trust this code? Are you sure it displayed
correctly in all editors? If you did not write it or your language is not
RTL, remove the special characters, as they could be used to trick you into
executing code, that does something else than what it looks like. More
Information: https://en.wikipedia.org/wiki/Bidirectional_text
https://trojansource.codes/

invalid-character-backspace (E2510)

Invalid unescaped character backspace, use «b» instead.
Moves the cursor back, so the character after it will overwrite the character
before.

invalid-character-carriage-return (E2511)

Invalid unescaped character carriage-return, use «r» instead.
Moves the cursor to the start of line, subsequent characters overwrite the
start of the line.

invalid-character-esc (E2513)

Invalid unescaped character esc, use «x1B» instead.
Commonly initiates escape codes which allow arbitrary control of the
terminal.

invalid-character-nul (E2514)

Invalid unescaped character nul, use «0» instead.
Mostly end of input for python.

invalid-character-sub (E2512)

Invalid unescaped character sub, use «x1A» instead.
Ctrl+Z «End of text» on Windows. Some programs (such as type) ignore the rest
of the file after it.

invalid-character-zero-width-space (E2515)

Invalid unescaped character zero-width-space, use «u200B» instead.
Invisible space character could hide real code execution.

invalid-unicode-codec (E2501)

UTF-16 and UTF-32 aren’t backward compatible. Use UTF-8 instead
For compatibility use UTF-8 instead of UTF-16/UTF-32. See also
https://bugs.python.org/issue1503789 for a history of this issue. And
https://softwareengineering.stackexchange.com/questions/102205/should-
utf-16-be-considered-harmful for some possible problems when using UTF-16 for
instance.

bad-file-encoding (C2503)

PEP8 recommends UTF-8 as encoding for Python files
PEP8 recommends UTF-8 default encoding for Python files. See
https://peps.python.org/pep-0008/#source-file-encoding

Unnecessary-Dunder-Call checker#

Verbatim name of the checker is unnecessary-dunder-call.

Unnecessary-Dunder-Call checker Messages#

unnecessary-dunder-call (C2801)

Unnecessarily calls dunder method %s. %s.
Used when a dunder method is manually called instead of using the
corresponding function/method/operator.

Unnecessary Ellipsis checker#

Verbatim name of the checker is unnecessary_ellipsis.

Unnecessary Ellipsis checker Messages#

unnecessary-ellipsis (W2301)

Unnecessary ellipsis constant
Used when the ellipsis constant is encountered and can be avoided. A line of
code consisting of an ellipsis is unnecessary if there is a docstring on the
preceding line or if there is a statement in the same scope.

Unsupported Version checker#

Verbatim name of the checker is unsupported_version.

Unsupported Version checker Messages#

using-f-string-in-unsupported-version (W2601)

F-strings are not supported by all versions included in the py-version setting
Used when the py-version set by the user is lower than 3.6 and pylint
encounters a f-string.

using-final-decorator-in-unsupported-version (W2602)

typing.final is not supported by all versions included in the py-version setting
Used when the py-version set by the user is lower than 3.8 and pylint
encounters a typing.final decorator.

Variables checker#

Verbatim name of the checker is variables.

See also variables checker’s options’ documentation

Variables checker Messages#

unpacking-non-sequence (E0633)

Attempting to unpack a non-sequence%s
Used when something which is not a sequence is used in an unpack assignment

invalid-all-format (E0605)

Invalid format for __all__, must be tuple or list
Used when __all__ has an invalid format.

potential-index-error (E0643)

Invalid index for iterable length
Emitted when an index used on an iterable goes beyond the length of that
iterable.

invalid-all-object (E0604)

Invalid object %r in __all__, must contain only strings
Used when an invalid (non-string) object occurs in __all__.

no-name-in-module (E0611)

No name %r in module %r
Used when a name cannot be found in a module.

undefined-variable (E0602)

Undefined variable %r
Used when an undefined variable is accessed.

undefined-all-variable (E0603)

Undefined variable name %r in __all__
Used when an undefined variable name is referenced in __all__.

used-before-assignment (E0601)

Using variable %r before assignment
Emitted when a local variable is accessed before its assignment took place.
Assignments in try blocks are assumed not to have occurred when evaluating
associated except/finally blocks. Assignments in except blocks are assumed
not to have occurred when evaluating statements outside the block, except
when the associated try block contains a return statement.

cell-var-from-loop (W0640)

Cell variable %s defined in loop
A variable used in a closure is defined in a loop. This will result in all
closures using the same value for the closed-over variable.

global-variable-undefined (W0601)

Global variable %r undefined at the module level
Used when a variable is defined through the «global» statement but the
variable is not defined in the module scope.

self-cls-assignment (W0642)

Invalid assignment to %s in method
Invalid assignment to self or cls in instance or class method respectively.

unbalanced-dict-unpacking (W0644)

Possible unbalanced dict unpacking with %s: left side has %d label%s, right side has %d value%s
Used when there is an unbalanced dict unpacking in assignment or for loop

unbalanced-tuple-unpacking (W0632)

Possible unbalanced tuple unpacking with sequence %s: left side has %d label%s, right side has %d value%s
Used when there is an unbalanced tuple unpacking in assignment

possibly-unused-variable (W0641)

Possibly unused variable %r
Used when a variable is defined but might not be used. The possibility comes
from the fact that locals() might be used, which could consume or not the
said variable

redefined-builtin (W0622)

Redefining built-in %r
Used when a variable or function override a built-in.

redefined-outer-name (W0621)

Redefining name %r from outer scope (line %s)
Used when a variable’s name hides a name defined in an outer scope or except
handler.

unused-import (W0611)

Unused %s
Used when an imported module or variable is not used.

unused-argument (W0613)

Unused argument %r
Used when a function or method argument is not used.

unused-wildcard-import (W0614)

Unused import(s) %s from wildcard import of %s
Used when an imported module or variable is not used from a ‘from X import
*’
style import.

unused-variable (W0612)

Unused variable %r
Used when a variable is defined but not used.

global-variable-not-assigned (W0602)

Using global for %r but no assignment is done
When a variable defined in the global scope is modified in an inner scope,
the ‘global’ keyword is required in the inner scope only if there is an
assignment operation done in the inner scope.

undefined-loop-variable (W0631)

Using possibly undefined loop variable %r
Used when a loop variable (i.e. defined by a for loop or a list comprehension
or a generator expression) is used outside the loop.

global-statement (W0603)

Using the global statement
Used when you use the «global» statement to update a global variable. Pylint
discourages its usage. That doesn’t mean you cannot use it!

global-at-module-level (W0604)

Using the global statement at the module level
Used when you use the «global» statement at the module level since it has no
effect.

Время прочтения
7 мин

Просмотры 125K


Автор: Анатолий Соловей, developer

Язык программирования Python очень востребован на современном рынке, он развивается изо дня в день, и вокруг него сложилось активное сообщество. Во избежание конфликтов между разработчиками-питонистами, создатели языка написали соглашение PEP 8, описывающее правила оформления кода, однако даже там отмечено, что:

Many projects have their own coding style guidelines. In the event of any conflicts, such project-specific guides take precedence for that project.

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

За долгое время работы у программистов вырабатывается собственный стиль написания кода, предпочтения в стайлгайдах и прочие мелочи, которые оставляют авторскую печать на программах девелопера. Убедить разработчиков отказаться от привычных им кодстайлов очень сложно, но, даже если это удастся, велик шанс, что в их коде будут проскакивать старые фишки, добавленные в силу привычки.

Когда каждый апдейт проходит строгий код ревью, включающий в себя проверку стилей, подобные ошибки могут очень сильно замедлять процесс разработки. А если ошибки в итоге не заметят даже в процессе ревью, в системе контроля версий проекта очень скоро появится куча нечитаемого и непонятного кода.

На помощь в этом случае приходят линтеры — инструменты, контролирующие оформление кода в проекте. Именно они помогают поддерживать его чистоту и, в нашем случае, предотвращать создание коммитов, которые могут содержать ошибки. Я для контроля качества использую Flake8 и сейчас постараюсь объяснить, почему выбрал именно его, и расскажу, как его настроить, чтобы получить максимальный результат. Заинтересовались? Добро пожаловать под кат.

Flake8: Your Tool For Style Guide Enforcement

Сам Flake8 — инструмент, позволяющий просканировать код проекта и обнаружить в нем стилистические ошибки и нарушения различных конвенций кода на Python.

Flake8 умеет работать не только с PEP 8, но и с другими правилами, к тому же поддерживает кастомные плагины, поэтому в дальнейшем в этой статье я буду отталкиваться от правил из Google Python Style Guide.

Почему Flake8?

Flake8: pep8 + pyflakes + more

Создатель Flake8 Тарек Зиаде ставил перед собой цель объединить главные популярные инструменты контроля кодстайла в одной библиотеке, с чем в итоге успешно справился — Flake8 получился действительно универсальным.

Легкость установки и конфигурации

Чтобы проверить, отвечает ли код в вашем проекте основным требованиям PEP 8, достаточно установить Flake:

$ pip install flake8

и запустить его — просто ввести в командной строке:

$ flake8 my_project

после чего вы получите список с именами файлов и номерами строк, где были допущены ошибки, и подробное описание самих ошибок:

$ flake8 my_project
myfile.py:1: 'sys' imported but unused
myfile.py:4:1: E302 expected 2 blank lines, found 1

Великолепно, не правда ли? Но и это не всё. Если вы не любитель работать с консолью, то вы можете настроить интеграцию Flake8 с IDE или редактором, который вы предпочитаете использовать.

Интеграция Flake8 с редакторами и IDE

Интеграция с PyCharm
Так же актуально и для любой другой IDE от JetBrains.
Интеграция проводится всего за пару несложных шагов.

Откройте настройки External Tools в File → Settings → Tools и нажмите на “+”, затем заполните поля по этому шаблону:

После этого нажмите на Output Filters, а затем на “+”, чтобы добавить новое правило для вывода сообщений от флейка:


Здесь мы говорим PyCharm, что хотим, чтобы в выводе строки с ошибками были кликабельными и открывали в редакторе файл и место с ошибкой

Все. Интеграция Flake8 с PyCharm закончена. Чтобы вызвать флейк и проверить свой код, кликаем правой кнопкой мыши на файл/директорию, которую мы хотим проверить, и в контекстном меню выбираем External Tools → Flake8.

В выводе PyCharm появится кликабельный список нарушений в выбранном файле/директории:

Интеграция с Atom
Чтобы установить инструмент Flake8 для Atom, используйте Atom package manager в Settings и найдите там linter-flake8:

Или вызовите


apm install flake8

из командной строки.

Затем перейдите в linter-flake8 settings и укажите путь к директории, где установлен flake8:

У linter-flake8 есть собственный ReadMe по настройке, с которым при желании вы можете ознакомиться на странице самого linter-flake8 в Atom.

Наличие Version Control Hooks

Именно это я считаю главным достоинством Flake8, которое выделяет его среди других линтеров. В отличии от большинства подобных инструментов, где для настройки VCS-хуков используются целые отдельные библиотеки и модули (как, например, в Pylint), настройка хуков в флейке проводится буквально в две строчки.

На момент написания этой статьи, Flake8 умеет использовать pre-commit-хуки для Git и Mercurial. Эти хуки позволяют, например, не допускать создания коммита при нарушении каких-либо правил оформления.

Установить хук для Git:

$ flake8 --install-hook git

И настроить сам гит, чтобы учитывать правила Flake8:

$ git config --bool flake8.strict true

Я продемонстрирую, как Git hook работает на проекте, который я использовал для примера интеграции Flake8 с PyCharm. В модуле flake8tutorial.py мы видим очевидные ошибки: импортированные и неиспользованные модули, остсутствие докстринга и пустой строки в конце файла.

Первым делом проинициализируем в этом проекте git-0репозиторий, установим flake8 хук и скажем нашему git, что он должен прогонять флейк перед коммитами:

Затем попробуем провести первый коммит:

Как видите, flake8 был вызван перед коммитом и не позволил нам закоммитить невалидные изменения.

Теперь фиксим ошибки, отмеченные флейком, и пытаемся закоммитить валидный код:

Коммит успешно создан. Отлично!

Настройка Flake8 для Mercurial практически идентична. Для начала нужно установить Flake8 Mercurial Hook:

$ flake8 --install-hook mercurial

И настроить сам Mercurial:

$ hg config flake8.strict true

Вот и все, хук для Меrcurial установлен, настроен и готов к использованию!

Подробнее о конфигурации Flake8

Базовая конфигурация

Список дополнительных опций и правил можно передать прямо при вызове из командной строки таким образом:

flake8 --select E123

(в этом примере опцией select мы говорим, чтобы Flake сообщал о нарушениях только правила E123 (это код правила “closing bracket does not match indentation of opening bracket’s line”)).

Кстати, полный список опций с описанием вы можете найти в документации к самой библиотеке.

На мой взгляд, куда предпочтительнее настраивать Flake с помощью конфигурационных файлов, вы можете хранить настройки в одном из файлов setup.cfg, tox.ini или.flake8. Для ясности я предпочитаю использовать последний вариант.

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

[flake8]
ignore = D203
exclude = .git,__pycache__,docs/source/conf.py,old,build,dist

В этом файле мы сообщаем Flake, что он не должен оповещать нас о нарушениях правила D203 (“1 blank line required before class docstring”), а также не должен проверять файлы .git, __pycache__, docs/source/conf.py и директории old, build, dist.

В конфигурационных файлах можно оставлять комментарии, это полезно делать, если вы предоставляете большой список правил, которые Flake должен игнорировать:

[flake8]
# it's not a bug that we aren't using all of hacking
ignore =
    # F812: list comprehension redefines ...
    F812,
    # H101: Use TODO(NAME)
    H101,
    # H202: assertRaises Exception too broad
    H202,
    # H233: Python 3.x incompatible use of print operator
    H233,
    # H301: one import per line
    H301,
    # H306: imports not in alphabetical order (time, os)
    H306,
    # H401: docstring should not start with a space
    H401,
    # H403: multi line docstrings should end on a new line
    H403,
    # H404: multi line docstring should start without a leading new line
    H404,
    # H405: multi line docstring summary not separated with an empty line
    H405,
    # H501: Do not use self.__dict__ for string formatting
    H501

Также можно добавить в исключения отдельную строку в вашем модуле, просто оставив на этой строке комментарий noqa. Тогда при проверке модуля Flake8 будет игнорировать ошибки, найденные в строках, помеченных этим комментарием:

import sys # noqa

Модули, расширяющие функциональность

Так как Flake позволяет создавать и использовать кастомные плагины, для него можно найти большое количество open-source плагинов. Я опишу только те, которые использую сам и считаю особенно полезными:

flake8-import-order

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

Этот плагин расширяет список предупреждений Flake, добавляя туда три новых:

  • I100: Your import statements are in the wrong order.
  • I101: The names in your from import are in the wrong order.
  • I201: Missing newline between sections or imports.

Установка:

pip install flake8-import-order

Конфигурация:

[flake8]
application-import-names = my_project, tests # Указываем флейку директории, в которых хранятся локальные пакеты.

import-order-style = google # Указываем флейку на то, в каком порядке должны идти импорты. Как я уже говорил выше, я предпочитаю использовать Google Style Guide.

Более подробно о настройке flake8-import-order можно прочитать на странице библиотеки на Github.

flake8-docstrings

Плагин, добавляющий поддержку функционала из pydocstyle — проверку докстрингов на соответствие конвенциям Питона.

Установка:

pip install flake8_docstrings

Список добавляемых этой библиотекой правил можно найти в документации pydocstyle.

Конфигурация:

Сама по себе эта библиотека никак не настраивается, однако добавленные правила можно внести в исключения, если какое-то из них неактуально для вашего проекта:

[flake8]
ignore = D101 # Игнорировать docstrings предупреждение “Missing docstring in public class”

Страница библиотеки на Github тут.

flake8-builtins

Плагин, проверяющий код на использование встроенных имен в качестве переменных или параметров.

Установка:

pip install flake8-builtins

Конфигурация:

Как и в случае с flake8-docstrings, у плагина нет дополнительных настроек, но добавленные им правила можно, например, внести в исключения флейка:

[flake8]
ignore = B001 # Игнорировать builtins предупреждение “<some_builtin> is a python builtin and is being shadowed, consider renaming the variable”

Более подробную информацию об этом плагине можно найти на странице этого плагина на Github.

flake8-quotes

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

Установка:

pip install flake8-quotes

Конфигурация:

[flake8]
inline-quotes = " # Указываем, какой тип кавычек должен использоваться в вашем проекте

Более подробную информацию об этом плагине можно найти на странице этого плагина на Github.

Послесловие

Хотя настройки, описанные выше, в 97,5 % случаев смогут предотвратить появление некачественного кода в репозитории, он так или иначе может оказаться запушенным (например, если деву было лень вводить две строчки для настройки pre-commit hook). Поэтому я настоятельно рекомендую добавить вызов Flake8 на этапе билда пул-реквестов в используемой вами системе continuous integration, чтобы предотвратить мердж невалидных пул-реквестов и попадание ошибок в мастер.

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

Список источников:

  • Документация Flake8
  • Useful Python Modules: Flake8
  • Google Python Style Guide

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