[PEP8] Take over the Python source code and write it neatly

At the beginning

If you look at programming language introduction sites, you will see that Python is described as a well-behaved language. I get the impression that Python has more restrictions on how to write it than other languages, but it still has a high degree of freedom, and when you actually develop it, a large amount of habits unique to each programmer will remain in the source.

This isn't a very important issue for personal hobbies, but it's a serious issue for work, especially for team development. Once developed, it basically has to be maintained for many years, and maintenance personnel often change during that period. It is very important to define the program rules in the project for later maintenance.

If you want to define the rules for each project, you can create it from scratch. However, since it takes time and cost, we often create coding standards based on PEP8, so I would like to introduce it.

What is PEP8

PEP8 is a Python coding standard created based on the idea that "code is read more often than written". By hijacking this convention, we aim to make the code easier to read and to make the style of code created by each programmer consistent.

In addition, PEP8 shows the attitude that it is not always necessary to comply with this agreement. I think it is better to flexibly create rules according to the characteristics of the project.

But be aware that there are times when you need to be inconsistent
That is, this style guide may not apply.
If in doubt, prioritize your judgment.
Look at other examples and decide which one looks best.

How to use

PEP8 itself is a convention, but a mechanism is provided that allows you to easily check whether the code can be written according to this convention.

pip install pep8

--Execute Specify the target source code in the argument and hit the pep8 command

pep8 test.py 

--Result

test.py:16:1: E302 expected 2 blank lines, found 1
test.py:22:80: E501 line too long (95 > 79 characters)
test.py:27:1: E302 expected 2 blank lines, found 1
test.py:39:1: E302 expected 2 blank lines, found 1
test.py:44:11: E225 missing whitespace around operator
test.py:46:12: E225 missing whitespace around operator
test.py:47:13: E225 missing whitespace around operator
test.py:50:27: W291 trailing whitespace
test.py:51:34: W291 trailing whitespace
test.py:60:45: W291 trailing whitespace
test.py:66:16: E231 missing whitespace after ':'
test.py:74:80: E501 line too long (90 > 79 characters)
test.py:90:10: E231 missing whitespace after ','
test.py:92:56: E231 missing whitespace after ','
test.py:101:1: W391 blank line at end of file

About the contents of the agreement

Here are some of the terms and conditions.

Indent

―― 1 Indent uses 4 spaces.

--If you want to continue the line, align the wrapped elements vertically. --Align to open brackets

foo = long_function_name(var_one, var_two,
                         var_three, var_four)

-Or add four spaces to distinguish between arguments and others

def long_function_name(
        var_one, var_two, var_three,
        var_four):

Tab or space

--A space-friendly indentation method.

Line length

--All line lengths up to 79 characters. --Line breaks use parentheses, brackets, and implicit line continuations in curly braces. --You can also use a backslash

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

Blank line

--Top-level functions and classes are defined with two lines apart. --Inside the class, define the method with one line at a time.

Source file encoding

--Use utf8

import

--The import statement should normally separate lines

#good: 
import os
import sys

#bad:  
import sys, os

--Specify the import statement with an absolute path except for exceptions

#good: 
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example

#bad:  
from . import sibling
from .sibling import example

--Imports are grouped below. --Standard library --Third party library --Specific to local applications / libraries

Whitespace characters in expressions and sentences

--Basically, do not put characters in expressions or sentences

#good: 
spam(ham[1], {eggs: 2})
#bad: 
spam( ham[ 1 ], { eggs: 2 } )

#good: 
foo = (0,)
#bad: 
bar = (0, )

#good: 
spam(1)
#bad: 
spam (1)

#good: 
dct['key'] = lst[index]
#bad: 
dct ['key'] = lst [index]

#good: 
x = 1
y = 2
long_variable = 3
#bad: 
x             = 1
y             = 2
long_variable = 3

Comma at the end

--It is usually optional to add a comma at the end. --Exceptionally required when creating a tuple with one element.

#good
FILES = ('setup.cfg',)

reference

https://pep8-ja.readthedocs.io/ja/latest/

Recommended Posts

[PEP8] Take over the Python source code and write it neatly
The process of making Python code object-oriented and improving it
[Python] Read the Flask source code
[Python] Read the source code of Bottle Part 2
[Python] Read the source code of Bottle Part 1
Let's write a Python program and run it
Fourier transform the wav file read by Python, reverse transform it, and write it again.
Since choreography is Wakaran, I will implement it and release the entire source code.
[Python3] Take a screenshot of a web page on the server and crop it further
Let's write python code that parses go code and generates go code
[Note] How to write QR code and description in the same image with python
Recursively get the Excel list in a specific folder with python and write it to Excel.
[Python / Ruby] Understanding with code How to get data from online and write it to CSV
[Python] I installed the game from pip and played it
Always check PEP8 while editing Python source code in Emacs
PyArmor ~ Easy way to encrypt and deliver python source code ~
Source installation and installation of Python
I downloaded the python source
First python ② Try to write code while examining the features of python
I wrote the code to write the code of Brainf * ck in python
Convert the result of python optparse to dict and utilize it
Code Python to check and graph if it follows Benford's law
The story of Python and the story of NaN
[Code] Module and Python version output
Write selenium test code in python
Check python code styles using pep8
How to write the correct shebang in Perl, Python and Ruby scripts
[Python] Sweet Is it sweet? About suites and expressions in the official documentation
I set the environment variable with Docker and displayed it in Python
Sample code to get the Twitter API oauth_token and oauth_token_secret in Python 2.7
Send and receive image data as JSON over the network with Python
Try to write python code to generate go code --Try porting JSON-to-Go and so on
Start the webcam to take a still image and save it locally
[python] Send the image captured from the webcam to the server and save it