PEP8: руководство по написанию чистого и читаемого кода на Python

Когда дело доходит до написания крупных проектов или поддержки существующего кода, становится очень важным следовать определенным стандартам кодирования, чтобы обеспечить читаемость, понятность и поддерживаемость кода.
Один из таких стандартов — PEP8, который устанавливает рекомендации по стилю и форматированию кода на языке Python.
Введение
PEP8 — это документ, описывающий стандарты, которые разработчики должны следовать при написании кода на Python. Следование этим рекомендациям может значительно улучшить качество вашего кода, сделать его более читаемым и понятным для других разработчиков.
В этой статье мы рассмотрим основные правила, описанные в PEP8, и объясним, как их следовать, чтобы написать чистый, читаемый и поддерживаемый код на Python.
Причины использовать
PEP8 — это руководство по стилю кода для языка программирования Python. Он описывает рекомендации и правила для написания читаемого, понятного и консистентного кода на Python.
PEP8 важен для написания качественного кода на Python по нескольким причинам. Во-первых, он помогает сделать код более читаемым и понятным для других программистов, которые могут работать с вашим кодом. Это особенно важно, если вы работаете в команде или если ваш код будет использоваться другими людьми.
Во-вторых, соблюдение стандартов PEP8 может помочь сделать ваш код более консистентным. Это означает, что ваш код будет выглядеть более единообразно и просто, что упрощает его понимание и обслуживание.
В-третьих, соблюдение стандартов PEP8 может помочь обнаружить ошибки и потенциальные проблемы в вашем коде. Например, если вы используете нестандартное именование переменных или не соблюдаете правила отступов, это может привести к ошибкам или проблемам при чтении вашего кода.
Кроме того, многие инструменты разработки поддерживают стандарты PEP8 и могут помочь вам автоматически проверять соответствие вашего кода этим стандартам.
В целом, соблюдение стандартов PEP8 является важной практикой для написания качественного кода на Python. Он помогает сделать ваш код более читаемым, консистентным и устойчивым к ошибкам.
Основные правила
Основные правила PEP8 — это набор рекомендаций по оформлению кода на Python, который помогает сделать код более читаемым и понятным. Ниже я перечислю несколько основных правил PEP8:
Отступы
Используйте 4 пробела для каждого уровня отступа. Это правило помогает визуально выделить блоки кода и упрощает чтение кода. Использование символов табуляции или пробелов для отступов не рекомендуется, так как это может вызывать проблемы с отображением в разных текстовых редакторах.
Например:
# Правильно: if x == 1: print("x is 1") # Неправильно: if x == 1: print("x is 1")
Максимальная длина строки
Ограничьте длину строки не более чем 79 символами. Если строка длиннее, разбейте ее на несколько строк. Длинные строки могут быть трудны для чтения, особенно когда они выходят за границы окна редактора. Разбиение длинных строк на несколько строк с помощью продолжения строки с помощью символа обратной косой черты \ является хорошей практикой.
Например:
# Правильно: long_string = "This is a really long string that "\ "spans multiple lines." # Неправильно: long_string = "This is a really long string that spans multiple lines."
Пробелы
Используйте один пробел между операторами и операндами. Не используйте пробелы для выделения скобок вокруг аргументов функций. Это правило помогает упростить код и сделать его более читабельным.
Например:
# Правильно: x = 2 + 3 y = (1 + 2) * 3 # Неправильно: x=2+3 y = ( 1 + 2 ) * 3
Именование
Используйте понятные и описательные имена переменных, функций и методов. Для имени переменных используйте строчные буквы, а для имен функций и методов — заглавные буквы. Это правило помогает делать ваш код более читаемым и понятным для других программистов.
Например:
# Правильно: age = 25 name = "John" def calculate_sum(numbers): return sum(numbers) # Неправильно: a = 25 b = "John" def calc_sum(nums): return sum(nums)
Комментарии
Добавляйте комментарии к вашему коду, чтобы объяснить сложные участки кода.
Комментарии должны быть короткими, лаконичными и описательными, они должны помогать другим программистам понимать ваш код. Не используйте комментарии для описания очевидных вещей, таких как присваивание переменной значения, и избегайте комментариев в конце строки.
Например:
# Правильно: # Получаем текущую дату и время current_time = datetime.datetime.now() # Неправильно: current_time = datetime.datetime.now() # Получаем текущую дату и время
Импорты
Импортируйте модули в алфавитном порядке, разделяйте группы импортов пустой строкой и избегайте использования символа * . Это правило помогает упростить импорты и улучшить читабельность кода.
# Правильно: import datetime import os from math import sqrt import requests # Неправильно: import requests, os, datetime from math import * import my_module
Пробелы вокруг операторов
Используйте пустые строки для разделения логически связанных частей кода. Не используйте несколько операторов на одной строке.
Используйте пробелы вокруг операторов (=, +, -, *, /, //, %, и т. д.), но не используйте пробелы вокруг символа индексирования или среза.
Например:
# Правильно: x = 2 + 3 y = x * 4 z = list[0] # Неправильно: x=2+3 y = x*4 z = list [0]
Названия функций и методов
Используйте глаголы в названиях функций и методов, используйте нижнее подчеркивание для разделения слов. Это правило помогает делать код более понятным и легче читаемым.
Например:
# Правильно: def calculate_sum(numbers): return sum(numbers) def get_user_name(user): return user.name # Неправильно: def numbersSum(nums): return sum(nums) def user(user): return user.name
Название переменных
Используйте понятные и описательные названия для переменных, избегайте использования одиночных символов в качестве названий переменных, используйте нижнее подчеркивание для разделения слов.
Например:
# Правильно: total_sum = 0 list_of_numbers = [1, 2, 3, 4] user_name = "John" # Неправильно: t = 0 n = [1, 2, 3, 4] un = "John"
Расположение функций и классов
Располагайте функции и классы логически в вашем коде. Разделяйте функции и классы пустыми строками, чтобы улучшить читабельность кода. Функции должны быть определены перед их использованием.
Например:
# Правильно: def calculate_sum(numbers): return sum(numbers) def main(): list_of_numbers = [1, 2, 3, 4] total_sum = calculate_sum(list_of_numbers) print(f"The total sum is: ") if __name__ == "__main__": main() # Неправильно: def main(): list_of_numbers = [1, 2, 3, 4] total_sum = calculate_sum(list_of_numbers) print(f"The total sum is: ") def calculate_sum(numbers): return sum(numbers) if __name__ == "__main__": main()
Длина строки
Строки не должны быть длиннее 79 символов. Если строка слишком длинная, ее можно разбить на несколько строк, используя скобки, запятые или операторы конкатенации.
Например:
# Правильно: message = "This is a very long message that should be split " \ "into multiple lines for better readability." total_sum = (100 + 200 + 300 + 400 + 500 + 600) # Неправильно: message = "This is a very long message that should be split into multiple lines for better readability." total_sum = 100 + 200 + 300 + 400 + 500 + 600
Тройные кавычки
Используйте тройные кавычки для документации вашего кода. Это помогает другим программистам понимать ваш код и использовать его в своих проектах.
Например:
# Правильно: def calculate_sum(numbers): """ This function calculates the sum of the numbers in the given list. Parameters: numbers (list): A list of numbers to calculate the sum of. Returns: float: The sum of the numbers in the list. """ return sum(numbers) # Неправильно: def calculate_sum(numbers): # This function calculates the sum of the numbers in the given list. return sum(numbers)
Полезные инструменты
Действительно, существует множество инструментов, которые помогают разработчикам Python следовать стандартам PEP8. Эти инструменты включают линтеры и автоматические форматировщики.
Линтеры — это инструменты, которые анализируют код и проверяют его соответствие стандартам PEP8. Они предупреждают разработчиков о нарушениях стандартов PEP8 и других проблемах в их коде. Некоторые из наиболее популярных линтеров для Python включают:
- pylint — это линтер для Python, который проверяет соответствие кода стандартам PEP8. Он также обнаруживает другие проблемы в коде, такие как синтаксические ошибки, неиспользуемые переменные и дублирование кода.
- flake8 — это линтер, который проверяет соответствие кода стандартам PEP8, а также обнаруживает другие проблемы в коде, такие как неиспользуемые импорты и неправильное форматирование строк.
- PyCharm — это IDE для Python, которая включает встроенный линтер, который проверяет соответствие кода стандартам PEP8 и другие проблемы в коде. Он также предлагает рекомендации по исправлению нарушений стандартов PEP8.
Автоматические форматировщики — это инструменты, которые автоматически форматируют код в соответствии со стандартами PEP8. Они упрощают процесс форматирования кода и позволяют разработчикам сосредоточиться на его содержимом. Некоторые из наиболее популярных автоматических форматировщиков для Python включают:
- Black — это автоматический форматировщик кода на Python, который форматирует код в соответствии со стандартами PEP8. Он удаляет неоднозначность в коде и делает его более понятным.
- autopep8 — это инструмент, который автоматически форматирует код в соответствии со стандартами PEP8. Он также может исправлять другие проблемы в коде, такие как синтаксические ошибки.
- YAPF — это автоматический форматировщик кода на Python, который форматирует код в соответствии со стандартами PEP8 и другими рекомендациями по стилю кодирования.
Использование линтеров и автоматических форматировщиков может значительно упростить процесс следования стандартам PEP8 и улучшить качество кода. Например, линтеры могут предупреждать о нарушениях стандартов PEP8 до того, как код будет отправлен на ревью, что помогает избежать ошибок, связанных со стилем кода. Автоматические форматировщики позволяют быстро и легко отформатировать код в соответствии со стандартами PEP8.
Кроме того, многие инструменты интегрируются с популярными средами разработки, такими как PyCharm и VS Code, что упрощает их использование и интеграцию в рабочий процесс разработки.
Важно отметить, что линтеры и автоматические форматировщики не могут полностью заменить ручное форматирование и проверку кода на соответствие стандартам PEP8. Иногда они могут допустить ошибки или предложить неоптимальные решения. Поэтому важно использовать эти инструменты в сочетании с ручной проверкой кода и соблюдением наилучших практик при написании кода на Python.
Дополнительные источники
Существует множество ресурсов и инструментов для дополнительного изучения PEP8 и его реализации в проектах.
Некоторые из них перечислены ниже:
- Официальный документ PEP8: Документ PEP8 можно найти на официальном сайте Python. Он содержит все основные правила и рекомендации по написанию чистого и понятного кода на Python.
- Flake8: Flake8 — это инструмент статического анализа кода на Python, который проверяет соответствие кода стандартам PEP8. Он также проверяет синтаксические ошибки, использование необъявленных переменных и другие нарушения.
- PyCharm: PyCharm — это интегрированная среда разработки (IDE) для Python, которая имеет встроенный инструмент PEP8. Он предупреждает вас, если ваш код нарушает стандарты PEP8, и предлагает исправления.
- Black: Black — это автоматический форматтер кода на Python, который следует стандартам PEP8. Он автоматически форматирует ваш код, чтобы он соответствовал стандартам PEP8, и также может использоваться для автоматического форматирования кода в больших проектах.
- pylint: pylint — это еще один инструмент статического анализа кода на Python, который проверяет соответствие кода стандартам PEP8. Он также предупреждает вас об использовании устаревших или небезопасных конструкций в вашем коде.
- Real Python: Real Python — это онлайн-платформа для изучения Python, которая содержит множество статей, учебных пособий и видеоуроков. Они предлагают руководства по написанию чистого и понятного кода на Python в соответствии с PEP8.
- Python Code Quality Authority: Python Code Quality Authority — это организация, которая управляет несколькими инструментами для проверки качества кода на Python, включая Flake8 и pylint. Они также поддерживают ряд стандартов и рекомендаций для написания чистого и понятного кода на Python.
Заключение
Следование правилам PEP8 поможет вам написать более чистый, понятный и поддерживаемый код на Python. Однако, не стоит забывать, что эти правила не являются абсолютными и всегда могут быть нарушены в некоторых случаях. Важно следить за своим стилем и придерживаться общепринятых стандартов в сообществе Python.
Как в PyCharm по клику привести код к PEP8?
Всем привет.
Можно ли как нибудь в PyCharm по нажатию конопки или комбинации, полностью весь код в файле привестии к PEP8 стандарту. То есть что бы удалились лишние энтеры, перенос строки, импорты лишние убрались и всё в этом духе.
Есть комбинация alt + ctrl + o, но она только импорты лишние дропает.
- Вопрос задан более трёх лет назад
- 15482 просмотра
1 комментарий
Простой 1 комментарий
Code Quality Assistance Tips and Tricks, or How to Make Your Code Look Pretty?
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. For more information about the Python language, please refer to the official website.
Before you start
- 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. For more information, refer to the product documentation.
- You have created a Python project ( File|New Project. ). For more information, refer to product documentation.
- You have created two directories src and test_dir ( File|New or Alt+Insert ).
- You have added Python files to the src and test_dir directories of your project( File|New or Alt+Insert ). For more information 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:

For more information, refer to Code Completion page of the product documentation.
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 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:

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 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 :

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:

So, as you can see, PyCharm supports PEP8 as the official Python style guide. If you explore the list of inspections ( Control+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 refer to 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 on the main toolbar, in the Settings dialog expand the node Appearance and Behavior , open the page Scopes. Then click and choose scope type Local .
In the Add New Scope dialog, 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:

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):

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

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:

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 Code|Inspect Code on the main menu, and in the dialog, choose the desired profile and 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:

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:

For more information, refer to this article.
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:
Next, press Alt+Enter and choose the intention action Create class ‘Solver’ :

Great! PyCharm has stubbed out a class:

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:

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’ :

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 Control+Alt+T (or choose Code | Surround with on the main menu):

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

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:

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:

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

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 Control+Alt+L (or choose Code | Reformat Code on the main menu):

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:

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:

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

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

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!):

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

Learn more about type hinting in the PyCharm documentation.
PyCharm shows «PEP8: expected 2 blank lines, found 1»
It always shows me: «expected 2 blank lines ,found 1» in a add_int_function , but not in the add_function . When I add two spaces in front of the def add_int_function(c, d): there is a error shows unindent does not match any outer indentation level in the end of add_function :

2,986 1 1 gold badge 28 28 silver badges 46 46 bronze badges
asked Oct 27, 2016 at 3:57
march_seven march_seven
691 2 2 gold badges 7 7 silver badges 13 13 bronze badges
If you find and answer useful, accept that answer by clicking on its check-mark (like here)so that other people will know the answer worked for you in the first look
Oct 27, 2016 at 12:24
PyCharm will fix it for you if you click on the code or press Alt-Enter and then click the yellow lightbulb and select Reformat file
Feb 7, 2018 at 3:16
4 Answers 4
Just add another line between your function definitions :


answered Oct 27, 2016 at 8:55
Kennet Celeste Kennet Celeste
4,603 3 3 gold badges 25 25 silver badges 34 34 bronze badges
@march_seven if this solved your issue you can accept the answer so that the others will immediately find out this solved the problem
Sep 15, 2017 at 14:25
Why is this necessary? What happens if there is just 1 line between the functions?
Feb 4, 2018 at 11:16
@FranzDeschler nothing happens, it just does not conform to the style guide, python.org/dev/peps/pep-0008/#blank-lines
Feb 7, 2018 at 3:10
Is it possible to turn this pep8 behaviour off?
Jun 30, 2019 at 22:56
@Leo Ufimtsev Go to Settings -> Editor -> Inspections -> Python -> PEP 8 coding style violation. Then press the check mark to disable it. You can also change the severity if you want to.
Aug 18, 2021 at 13:15
This is a pretty common question within the python community. After the release of PEP 8, new formatting styles were accepted into python. One of them states that after the definition of a class or function there must be two lines separating them. As such:
def yadayada: print("two lines between the functions") def secondyadayada: print("this is the proper formatting")
So, you should never do it like:
def yadayada: print("two lines between the functions") def secondyadayada: print("this is the proper formatting")
Or else PyCharm will throw that error at you.