Как исправить все ошибки pep8 в pycharm

What this tutorial is about

This tutorial aims to walk you step by step through creating source code in a Python project, with the use of PyCharm’s code intelligence features. You will see how PyCharm helps keep your source code in perfect shape, with proper indentations, spaces, imports etc. – actually, you’ll see that PyCharm itself is a code quality tool.

Python programming is out of scope of this tutorial. To learn more about the Python language, please refer to the official website.

Before you start

Make sure that:

  • You are working with PyCharm version 5.0 or later. If you still do not have PyCharm, download it from this page. To install PyCharm, follow the instructions, depending on your platform. Refer to the product documentation for details.

  • You have created a Python project (). Refer to the product documentation for details.

  • You have created two directories src and test_dir ( or Alt+Insert).

  • You have added Python files to the src and test_dir directories of your project( or Alt+Insert). To learn about creating files, refer to the section Populate projects.

Highliting code style violations

Create a new Python file src/Solver.py Alt+Insert. The created file immediately opens for editing. The file by default has no contents – this is because the file Solver.py is created by a file template that (in the case of Python files) contains just nothing.

Next, start typing the keyword class. When you just start typing, PyCharm immediately shows the suggestion list to complete your code:

Py code1

(Refer to Code Completion page of the product documentation for details.)

The red curve marks the next expected entry – in this case, this is the expected identifier. Enter the class name Solver. The red curve moves after the class name. If you hover your mouse pointer over this curve, you see the error description (“Colon expected”). Also, mind the red error stripe in the right gutter – it also marks the same error:

Py colon expected

OK, type the colon, and press Enter. According to the Python code style, the next statement is indented. If by chance you press space after Enter, you will thus violate the code style settings.

Tuning the PEP8 inspections

However, by default these violation are but weak warnings, and as such, are not visible. So, at first, let’s raise their importance. Click App general settings on the main toolbar, on the Inspections page of the Settings dialog, type PEP8 to find all PEP8-related inspections, and from the Severity drop-down list, choose Warning:

Py inspection severity

Apply changes and close the dialog. Now let’s return to our source code.

Tracking PEP8 rules

Now PyCharm shows its best! It stands on guard to protect your code style integrity. You immediately note that indented space is highlighted, and, when you type the next statement, for example, def demo(self,a,b,c):, PyCharm will show the message from the PEP8 inspection:

Py inspection pep8

So, as you can see, PyCharm supports PEP8 as the official Python style guide. If you explore the list of inspections (Ctrl+Alt+S – Inspections), you will see that PyCharm launches the pep8.py tool on your code, and pinpoints the code style violations.

Code inspections and their settings

Btw, look at the Inspections more attentively. If you have just opened this page, you see the default inspection profile with the default settings: it means that the inspections apply to all the sources of the current project.

Let’s try to customize this profile for two different scopes:

  • In the Test scope, the spelling errors should be marked as typos (green)

  • In the Production scope, the spelling errors should be marked as errors (red) – can we actually produce code with typos?

This is how it’s done…

Creating scopes

First, let’s define the two scopes. To do that, click App general settings on the main toolbar, in the Settings dialog box expand the node Appearance and Behavior, open the page Scopes. Then click App general add and choose scope type Local.

In the Add New Scope dialog box, type the scope name (Test), and then, in the project tree, choose the directory to be included in the Test scope, test_dir. Note that the Pattern field is filled in automatically, as you include the directory:

Py scope test

Repeat this process to create the Production scope.

Creating inspection profile with these scopes

Next, let’s create a copy of the default profile (though this profile is editable… just to be on the safe side):

Py copy profile

and give it a new name, for example, MyProjectProfile. This new profile is a copy of the default one, and has the same set of inspections.

With this new profile selected, let’s locate the Spelling inspection and change it. To find the Spelling inspection (we’ve already done it before), just type spel in the search area.

What’s next? Click In All Scopes button and select the Test scope from the list; repeat same for the Production scope

Py spel test scope

In the scope “Test”, the inspection severity is left as-is (a typo); however, the scope “Production” we’ll choose “Error” from the list of severities:

Py spel production scope

Mind the color code of inspections. They are shown black if unchanged. If they are blue, then it means that they have been changed.

Apply changes and close the dialog…

So, the modified inspection profile is ready. Its name is Project Default (copy), and it has different settings for the Spelling inspection in the Test and Production scopes. Next, let’s inspect code against this profile. To do that, choose on the main menu, and in the dialog box, choose the desired profile and scope:

Py inspect code against scope

Do it twice – for Test and Production scopes (if you want to preserve inspection results for further examination and sharing, you can export them). Explore results:

Py spel inspection

Highlighting errors

Besides coding style violations, PyCharm highlights the other errors too, depending on the selected profile.

For example, if your inspection profile includes Python inspection Unresolved references, and you use a symbol that not yet has been imported, PyCharm underlines the unresolved reference and suggests to add import statement:

Py import

Refer to the product documentation.

Generating source code

PyCharm provides lots of possibilities to automatically generate code. You can explore the auto-generation features in the product documentation. Let’s explore the main code generation procedures. To do that, just delete all contents of the file Solver.py, and start from scratch.

First, create an instance of a class:

Py create instance of a class

Next, press Alt+Enter and choose the intention action Create class ‘Solver’:

Py create class intention action

Great! PyCharm has stubbed out a class:

Py create class stub

Next, let’s add a method to the class instance. To do that, type a dot after class instance, and then type the method name. This method does not yet exist, and PyCharm suggests to create one:

Py create method in class

Let’s do some manual work – type the source code. When it comes to calculate the discriminant, we have to extract a square root. There is a dedicated function sqrt in the library math, but it is not yet imported. OK, let’s type it anyway, and see how PyCharm copes with it. Press Alt+Enter and choose Import ‘math’:

Py create import

So, we’ve come to the source code like this:

import math
class Solver(object):
def demo(self,a,b,c):
d = b ** 2 – 4 * a * c
disc = math.sqrt(d)
root1 = (- b + disc) / (2 * a)
root2 = (- b – disc) / (2 * a)
print (root1, root2)
return root1, root2

However, it lacks some significant analysis. We’d like to analyze the radicand d. If it is zero or positive, then the discriminant and the equation roots will be calculated; when the radicand is negative, let’s raise an exception. How PyCharm will help complete this task?

Let’s surround a block of code with if construct. Select the statements to be completed, when d is non-negative, and press Ctrl+Alt+T (or choose on the main menu):

Py surround code

Select if option from the suggestion list. As you see, PyCharm automatically adds if True: and indents the selected lines:

Py surround added

We are not at all interested in a boolean expression, so let’s change the selected True to d >= 0. Next, place the caret at the end of the last line, and press Enter. The caret rests on the next line, with the same indentation as the if statement; type the else: clause here, and see PyCharm reporting about the expected indentation:

Py else indent expected

When you press Enter again, the caret rests at the indented position. Here you can type the exception expression, using PyCharm’s powerful automatic code completion:

Py completing code

Reformatting code

Let’s look again at our Solver.py file. Its right gutter shows yellow stripes. When you hover your mouse pointer over a stripe, PyCharm shows the description of the corresponding problem in the code:

Py warnings

The good news is that they are but warnings, and won’t affect the results. Bad news is they are too numerous to fix each one by one. Is it possible to make the source code nice and pretty without much fuss?

PyCharm says – yes. This is the code reformatting feature. So let’s try to change formatting of the entire file. To do that, press Ctrl+Alt+L (or choose on the main menu):

Py reformat code done

Look at the code now – the PEP8-related drawbacks are all gone.

Note that you can define formatting rules yourself. To do that, open the code style settings, select language (in this case, Python), and make the necessary changes:

Py reformat code settings

Adding documentation comments

OK, formatting is fixed now, but there are still some stripes left. The inevitable yellow light bulb shows the possibility to add a docstring comment:

Py intention docstrings

Choose this suggestion and see the docstring comment for a certain parameter added:

Py intention docstrings done

Note that you have to select the checkbox Insert type placeholders in documentation comment strings in the Smart Keys page of the Editor settings:

Py insert type placeholder setting

There are several docstring formats, and the documentation comments are created in the format, which you have selected in the Python Integrated Tools page. If you so wish, you can change the docstring format to, say, Epytext or plain text.

Type hinting

The documentation comments can be used to define the expected types of parameters, return values, or local variables. Why do we need it all? For example, we’d like to keep under control the types of parameters we pass to the demo() method. To do that, let’s add the corresponding information to the documentation comment (By the way, mind code completion in the documentation comments!):

Py docstrings completion

Next, when you look at the method invocation, you see that the wrong parameter is highlighted by the PyCharm’s inspection Type Checker:

Py type checker

Learn more about type hinting in the PyCharm documentation.

Last modified: 11 January 2023

I’ve been having this PEP8 style highlighting issue. The issue is it’s not highlighting obvious style issues, like no blank lines before class definitions, or no empty lines at the end of the file. It could have to do with my VM and vagrant, but the project code is hosted locally so I don’t think that should be an issue.

If I do Code > Run Inspection By Name > PEP 8 coding style violation it says it finds no instances.

Under File > Settings > Editor > Code Style > Python > Blank Lines I have blank lines set around the class. An oddity is that if I change the number of lines “around method”, it changes them in real time in the example text on the right, but it doesn’t do the same for lines “around class”.

Under File > Settings > Editor > Inspections > Python I have “PEP 8 coding style violation” selected. I’ve tried changing it from warning to error and I still can’t see the highlights in my file.

I don’t have power saver mode on, which I’ve learned is a way to deactivate the background style checking in the editor.

I searched in Help > Show Log in Files for PEP8 and found “Pep8ExternalAnnotator – Found no suitable interpreter”, but I don’t know what that means and I couldn’t find any references to it online.

I’m running PyCharms professional 2016.3

PyCharm 2016.3.2
Build #PY-163.10154.50, built on December 28, 2016
Licensed to arbaerbearfaerfa
Subscription is active until October 17, 2017
For educational use only.
JRE: 1.8.0_112-release-408-b6 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Время прочтения: 4 мин.

Недавно я готовил доклад на тему “ Autopep8” и подчерпнул для себя много полезной информации. Немного подумав, решил поделиться ею с вами.

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

Исходя из технической документации, autopep8 исправляет следующие ошибки, о которых сообщает pycodestyle, например:

— серия ошибок E100 – исправление визуальных отступов.

— серия ошибок E200 – прибавление отсутствующих пробелов или удаление лишних.

— серия ошибок E300 – исправления, связанные с отсутствием или присутствием лишних пустых строк.

— серия ошибок E400 – исправления, связанные с импортом модулей.

— серия ошибок W290 – удаление лишних завершающих пробелов в последней строке и добавление пустой завершающей строки, в случае ее отсутствия.

Для установки Autopep8 необходимо в терминале выполнить команду:

 $ pip install autopep8 После установки открываю Pycharm, создаю новый файл Python, называю его, к примеру, main.py. Далее необходимо добавить в файл, рандомный код, который представлен на картинке ниже:

Этот код выглядят небрежно, элементы словаря расписаны в несколько строчек, смещены отступы в строчках словаря, в некоторых местах элементы словаря склеились, проставлены лишние пробелы после словаря, скобка, закрывающая словарь опущена на строчку ниже. В объявлении функции summa склеились аргументы, а в самой функции склеились элементы возвращаемой суммы. Импорт модулей расположен в конце написанного кода, и в целом по коду присутствуют разрывы и склеивания в виде присутствия большого количества пробелов или их отсутствия. Теперь необходимо воспользоваться  модулем Autopep8. В терминале, находясь в директории с файлом проекта, ввожу следующую команду:

 $ autopep8 --in-place --aggressive main.py

Получаю код следующего вида:

Теперь код выглядит более лаконичным  и красивым. Все склейки устранены, отступы соблюдены, импорты модулей перенесены в начало кода. Но все равно структура кода еще не идеальна – элементы словаря не упорядочены по одному в каждой строке, закрывающая скобка словаря находится, через строку, ниже. Применяю усиливающее свойство нашей команды. В терминале, при вводе команды, дублирую «—aggressive»:

 $ autopep8 --in-place --aggressive --aggressive main.py

Получаю код следующего вида:

Теперь код выглядит практически идеально =)

Снова возвращаюсь к начальному неисправленному коду.

Чтобы включить только часть исправлений, нужно использовать параметр – select. Например, чтобы исправить различные типы проблем с отступами, ввожу команду:

 $ autopep8 --select=E1 --in-place --aggressive main.py

Получаю следующий вид кода:

В итоге autopep8 исправил отступы внутри словаря.

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

1: File --->  Settings  --->  Tools  --->   External Tools

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

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

Tools  —> External Tools —> pep8. И просто щелкнуть мышью.

Теперь, что хочется сказать в заключении… Инструмент Autopep8 прост в установке, гибок в использовании и автоматически приводит ваш код к стандарту PEP8. А какие линтеры, автоформатеры знаете Вы? =) Делитесь в комментариях.

E1 Indentation E101 indentation contains mixed spaces and tabs E111 indentation is not a multiple of four E112 expected an indented block E113 unexpected indentation E114 indentation is not a multiple of four (comment) E115 expected an indented block (comment) E116 unexpected indentation (comment) E117 over-indented E121 (*^) continuation line under-indented for hanging indent E122 (^) continuation line missing indentation or outdented E123 (*) closing bracket does not match indentation of opening bracket’s line E124 (^) closing bracket does not match visual indentation E125 (^) continuation line with same indent as next logical line E126 (*^) continuation line over-indented for hanging indent E127 (^) continuation line over-indented for visual indent E128 (^) continuation line under-indented for visual indent E129 (^) visually indented line with same indent as next logical line E131 (^) continuation line unaligned for hanging indent E133 (*) closing bracket is missing indentation     E2 Whitespace E201 whitespace after ‘(‘ E202 whitespace before ‘)’ E203 whitespace before ‘:’     E211 whitespace before ‘(‘     E221 multiple spaces before operator E222 multiple spaces after operator E223 tab before operator E224 tab after operator E225 missing whitespace around operator E226 (*) missing whitespace around arithmetic operator E227 missing whitespace around bitwise or shift operator E228 missing whitespace around modulo operator     E231 missing whitespace after ‘,’, ‘;’, or ‘:’     E241 (*) multiple spaces after ‘,’ E242 (*) tab after ‘,’     E251 unexpected spaces around keyword / parameter equals     E261 at least two spaces before inline comment E262 inline comment should start with ‘# ‘ E265 block comment should start with ‘# ‘ E266 too many leading ‘#’ for block comment     E271 multiple spaces after keyword E272 multiple spaces before keyword E273 tab after keyword E274 tab before keyword E275 missing whitespace after keyword     E3 Blank line E301 expected 1 blank line, found 0 E302 expected 2 blank lines, found 0 E303 too many blank lines (3) E304 blank lines found after function decorator E305 expected 2 blank lines after end of function or class E306 expected 1 blank line before a nested definition     E4 Import E401 multiple imports on one line E402 module level import not at top of file     E5 Line length E501 (^) line too long (82 > 79 characters) E502 the backslash is redundant between brackets     E7 Statement E701 multiple statements on one line (colon) E702 multiple statements on one line (semicolon) E703 statement ends with a semicolon E704 (*) multiple statements on one line (def) E711 (^) comparison to None should be ‘if cond is None:’ E712 (^) comparison to True should be ‘if cond is True:’ or ‘if cond:’ E713 test for membership should be ‘not in’ E714 test for object identity should be ‘is not’ E721 (^) do not compare types, use ‘isinstance()’ E722 do not use bare except, specify exception instead E731 do not assign a lambda expression, use a def E741 do not use variables named ‘l’, ‘O’, or ‘I’ E742 do not define classes named ‘l’, ‘O’, or ‘I’ E743 do not define functions named ‘l’, ‘O’, or ‘I’     E9 Runtime E901 SyntaxError or IndentationError E902 IOError     W1 Indentation warning W191 indentation contains tabs     W2 Whitespace warning W291 trailing whitespace W292 no newline at end of file W293 blank line contains whitespace     W3 Blank line warning W391 blank line at end of file     W5 Line break warning W503 (*) line break before binary operator W504 (*) line break after binary operator W505 (*^) doc line too long (82 > 79 characters)     W6 Deprecation warning W601 .has_key() is deprecated, use ‘in’ W602 deprecated form of raising exception W603 ‘<>’ is deprecated, use ‘!=’ W604 backticks are deprecated, use ‘repr()’ W605 invalid escape sequence ‘x’ W606 ‘async’ and ‘await’ are reserved keywords starting with Python 3.7

Rui Sun

Rui Sun

Ph.D. student
Biomedical Engineering
Carnegie Mellon University

  • GitHub

less than 1 minute read

Taken from https://gist.github.com/StefanoMagrassi/6c78b6f48599377a5c805fd58a5cd93d

  1. Go to settings, search for Inspections (Under Editor, Code style)
  2. Find and click PEP8 code style violation. In the right panel, there is ignore errors option.
  3. Find the error code of interest, e.g. E501 line too long here, and paste the code to Pycharm.
  4. Ok the setting.

Добавить комментарий