This section describes the Python coding conventions.
Python has a coding standard called PEP8. The outline specified in PEP8 is shown below.
In the import statement, do not use ʻimport os, sys`, etc., but divide it into multiple lines as shown below. Also, insert a blank line to distinguish between standard libraries, third-party libraries, local modules, etc.
import os
import sys
from django.utils import timezone
from my_app.models import User
a = 1
b = a + 2
list_nums = [a, b]
dict_nums = {'a': a, 'b': b}
Insert a half-width space before and after =
, and put a half-width space after ,
in lists and dictionaries.
Also, put a space after the :
in the dictionary.
When defining a ʻif statement, a
forstatement, a function or a class, start writing the line after the
:` by indenting four half-width spaces (and multiples thereof).
if True:
print("It's true.")
Leave two lines before top-level function or class definitions. Leave one line free for methods in the class.
def my_func():
return 'my_func'
class MyClass():
name = my_class
def print_name(self):
return self.name
The number of characters in one line is basically 79 characters or less. For docstring, use 72 characters or less.
There is flake8
as a tool to check if the source code complies with PEP8.
It can be executed with the following command.
$flake8 filename.py
When executed, it will show you which parts of the source code do not meet what coding conventions.
Here, I explained the coding standard of Python. Python is a readability language, so it's essential for writing code that is easy for others to read.
Recommended Posts