Python code writing specification

Python code writing specification

I've been writing some recently Python The program has not specifically understood the code writing specifications before. Here, some specifications are sorted out to be more in line with the industry specifications and conducive to reading by yourself and others.

Summary of key points

  • Requires 4 space indents instead of tabs
  • Pay attention to the code length, no more than 79 characters per line, and use newline characters appropriately
  • Pay attention to appropriate blank lines of code to better distinguish code areas
  • Code comments and document comments must be correct and updated first
  • The source code coding format is unified using utf-8, or consistent with the old file code
  • The naming of files, classes, functions and even variables should be standardized, and Chinese should not be used
  • It is important to realize that code is read much more often than written

Space

  • It is recommended to use spaces between the two sides of the operator and between the function parameters
  • There should be no spaces on either side of the bracket
  • Don't have spaces before commas, semicolons, colons, but you should add them after them (except at the end of the line)
  • When = is used to indicate a keyword parameter or default parameter value, do not use spaces on both sides of it
  • Avoid unnecessary spaces and do not add spaces for alignment

Blank line

  • The definition of top-level functions and classes is separated by two empty lines
  • The method definitions in the class are separated by a blank line
  • Related functional groups can be separated by additional blank lines (use with caution)
  • Blank lines between a pile of identical single line codes can be omitted
  • Use empty lines in functions to distinguish logical segments (use caution)

notes

  • General principle: wrong comments are better than no comments. When a piece of code changes, the first thing is to modify the comments
  • The notes must be in English, preferably a complete sentence with capital letters. There is a closing character after the sentence, followed by two spaces to start the next sentence. If it is a phrase, the terminator can be omitted
  • Block comments: comments added before a piece of code, with a space after # and only # line spacing between paragraphs
# Description : Module config.  
#
# Input : None
#
# Output : None
  • Line note: when adding comments after a sentence of code, you should leave 2 spaces away from the code, but this method should be used as little as possible
  • Avoid unnecessary comments
  • There is no need to vertically align tags between multiple lines with spaces, which will cause the burden of maintenance
  • Document string: document all common modules, functions, classes, and methods. Non public methods are not necessary, but there should be a note describing the specific role of the method. This comment should be after the def line. For a single line document description, the three quotation marks at the end should be on the same line as the document. In particular, it should be noted that the closing three quotation marks used in the multi line document description should form a single line.

loop

  • You should avoid using the + and + = operators to accumulate strings in the loop, because the strings are immutable, which will create unnecessary temporary objects. The recommended practice is to add each string to the list, and then use the join() method to connect the list after the loop ends

Long statement

  • In addition to long import statements and URL s in comments, try not to exceed 80 characters per line, and try to avoid using backslashes to connect lines
  • You can add a pair of extra parentheses around the expression to connect different rows, because Python implicitly connects the rows in parentheses, brackets, and curly braces
  • In the comment, place the long URL on one line if necessary

Import module

  • Use import or from... Import to import the corresponding module
  • Try not to use the pattern of wildcard import (from some module import *), because variables in the namespace may cause conflicts
# no
from somemodule import *

# yes
import somemodule as sm
from somemodule import (func1, func2, func3, func4, func5)
  • The module import is always at the top of the file, after the module comment and document string, before the module's global variables and constants
  • Module import is grouped in the following order: standard library import, related third-party library import, local application / library specific import; And add a blank line between each group of imports
  • Absolute path import is recommended
  • When importing a class from a module containing a class, you need to consider whether it will lead to name conflicts
# When names do not conflict
from myclass import MyClass
from foo.bar.yourclass import YourClass

# When names conflict
import myclass
import foo.bar.yourclass

myclass.MyClass
foo.bar.yourclass.YourClass
  • Each import statement only imports one module. Try to avoid importing multiple modules in turn

Reserved word

  • A reserved word is a keyword and cannot be used as the name of any identifier
  • Python's standard library provides a keyword module that can output all keywords of the current version
import keyword
print(keyword.kwlist)

Naming conventions

  • The function name should be as short as possible and use lowercase letters. If you want to improve readability, you can use underline segmentation
  • The class name adopts the hump naming method of capitalized words, such as GetMoney, History, etc
  • Module variables or functions starting with a single underscore are protected. When importing from a module using the import * from statement, these variables or functions cannot be imported
  • Variables or methods that begin with a double underscore are private
  • Do not use the letters l, O and I as single character variable names, which is easy to be confused

indent

  • Use 4 spaces for each level of indentation. Be sure to follow an indentation after colon line feed, otherwise there will be syntax errors
  • Consecutive lines should align folded elements, whether they are vertical implicit line connections or using hanging indents (the first line has no parameters and uses more indents to distinguish itself from consecutive lines)
# Align with delimiter
foo = long_function_time(var_one, var_two,
						 var_three. var_four)

# Include more indents to distinguish from other lines
def long_function_name(
		var_one, var,two, var_three,
		var_four):
	print(var_one)

# The hanging indent should be increased by one level
foo = long_function_name(
	var_one, var_two, var_three,
	var_four)						 
  • When the conditional part of the if statement is long enough to be written on a new line, Note that it can be used at the connection of two character keywords (for example, if), add a space and an open parenthesis to create a 4-space indented multi line condition. However, this will have a visual conflict with the code that also uses 4-space indentation in the if statement. For how to visually further distinguish these condition lines from the nested suite in the if statement, the available options include but are not limited to the following:
# No extra indentation
if (this_is_one_thing and
	that_is_another_thing):
	do_something()

# Add a comment to make some distinctions in the editor that can provide syntax highlighting
if (this_is_one_thing and
	that_is_another_thing):
	# Since both conditions are ture, we can frobnicate.
	do_something()

# Add additional indents to conditional statements
if (this_is_one_thing and
		that_is_another_thing):
	do_something()
  • In a multiline structure, the closing brackets of braces / brackets / braces can be aligned with the content, and a separate line can be used as the first character of the last line
# Can be aligned with the first non white space character on the last line
my_list = [
	1, 2, 3,
	4, 5, 6,
	]

# Can be aligned with the first character of the last line
my_list = [
	1, 2, 3,
	4, 5, 6,
]
  • Wrapping before binary operators follows the tradition of mathematics, which makes it easy to match operators and operands
# Recommendation: operators and operands are easy to match
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

Keywords: Python Code Style

Added by kirk112 on Sun, 26 Dec 2021 18:50:21 +0200