As the saying goes: "No rules inadequate surrounding area". Programming is often done in a team, so a consistent coding specification is necessary so that the code written is easy for other people on the team to read and read later by the writer.
Tips
The Python code specification for this book draws on Python's official PEP8 encoding specification ^1 and Google Python coding specification ^2.
Naming conventions
There are identifiers everywhere in the program code, so it is important to take a consistent and canonical name. There are many different naming conventions in Python. Different code elements are named differently, as described in the following categories.
The package name. All lowercase letters, which can be separated by dots, are not recommended for use with underscores. As a namespace, the package name should be unique, and it is recommended to use an inverted corporate or organizational domain name, such as Com.apple.quicktime.v2.
The module name. All lowercase letters, if multiple words are composed, can be separated by underscores, such as dummy_threading.
The class name. Using the big hump method named ^3, such as Splitviewcontroller.
The name of the exception. Exceptions belong to a class, naming similar names, but should use error as a suffix. such as Filenotfounderror.
The variable name. All lowercase letters, if multiple words are composed, can be separated by an underscore. If a variable is applied to the inside of a module or function, the variable name can begin with a single underscore, or the variable name can begin with a double underscore if the variables class is private. Do not name the variable with the beginning and end of the double underscore, which is reserved by Python. Also, avoid using lowercase l, uppercase O, and uppercase I as variable names.
The function name and method name. Name the same variable name. such as Balance_account, _push_cm_exit.
- The constant name. All uppercase letters, if made up of multiple words, can be separated by underscores, such as year and Week_of_month.
Examples of naming conventions are:
_saltchars = _string.ascii_letters + _string.digits + ‘./‘def mksalt(method=None): if method is None: method = methods[0] s = ‘${}$‘.format(method.ident) if method.ident else ‘‘ s += ‘‘.join(_sr.choice(_saltchars) for char in range(method.salt_chars)) return sMETHOD_SHA256 = _Method(‘SHA256‘, ‘5‘, 16, 63)METHOD_SHA512 = _Method(‘SHA512‘, ‘6‘, 16, 106)methods = []for _method in (METHOD_SHA512, METHOD_SHA256, METHOD_MD5, METHOD_CRYPT): _result = crypt(‘‘, _method) if _result and len(_result) == _method.total_size: methods.append(_method)
Annotation specification
There are three types of annotations in Python: single-line comments, multiline comments, and document annotations. This section describes how to standardize the use of these annotations.
File comments
A file comment is a comment that is added at the beginning of each file, with multiple lines of comments. File comments usually include the following information: Copyright information, file name, module, author information, historical version information, file content and function.
Here is an example of a file comment:
# # 版权所有 2015 北京智捷东方科技有限公司# 许可信息查看LICENSE.txt文件# 描述:# 实现日期基本功能# 历史版本:# 2015-7-22: 创建 关东升# 2015-8-20: 添加socket库# 2015-8-22: 添加math库#
The above comment only provides the copyright information, the file content and the historical version information and so on, the document annotation must include the content according to own actual situation.
Document comments
A document comment is a document string that can generate an API help document that can be extracted from a Python source code file using the official Python Pydoc tool, or an HTML file can be generated. All public modules, functions, classes, and methods should be annotated with documentation.
The documentation annotation specification is somewhat "harsh". Document comments recommend using a pair of triple double quotation marks ("" ") wrapped up, note that the use of triple single quotation marks (" ") is not recommended. The document comments should be in the first statement inside the module, function, class, and method that is commented on. If a document comment line can be commented on, the end of the triple double quotation mark is also on the same line. If the document comment is long, leave a blank line after the first line comment, and then the rest of the comment content, the comment wrapping is to begin the triple double quotation mark Alignment, the last triple double quotation mark to be exclusive line, and the beginning triple double quotation marks to align.
The following code is part of the official Python-provided base64.py file.
#! /usr/bin/env python3 "" "Base16, Base32, Base64 (RFC 3548), Base85 and Ascii85 data Encodings" "" ①# Modified 04-oct-1995 by Jack Jansen to use Binascii module# Modified 30-dec-2003 by Barry Warsaw to add full RFC 3548 support# Modified 22-may-20 Guido van Rossum to use bytes everywhereimport reimport structimport binasciibytes_types = (bytes, bytearray) # TYP Es acceptable as binary datadef _bytes_from_decode_data (s): ②if isinstance (S, str): Try:return s.en Code (' ASCII ') except Unicodeencodeerror:raise valueerror (' string argument should contain only ASCII Cha Racters ') if Isinstance (S, bytes_types): return s Try:return memoryview (s). Tobytes () except Typeer Ror:raise TypeError ("argument should is a Bytes-like object or ASCII" "string, not%r"% s . __class__.__name__) from none# Base64 encoding/decoding uses binasciidef b64encode (S, altchars=none): "" "Encode the Tes-like Object S USINg Base64 and return a bytes object. ③optional Altchars should be a byte string of length 2 which specifies an④alternative alphabet for the ' + ' and '/' characters. This allows a application to e.g. generate URL or filesystem safe Base64 strings. "" "⑤encoded = Binascii.b2a_base64 (S, newline=false) if Altchars is not None:assert len (altchars) = = 2, Rep R (Altchars) return encoded.translate (Bytes.maketrans (b ' +/', altchars)) return encoded
The above code ① line is only one line of the document comments, code ③ line \~ ⑤ Line is a multi-line document comment, note that its first line is followed by a blank line, the code ④ line followed by comments, it is to start with the triple double quotation marks aligned. The code ⑤ line is the end of the triple double quotation mark, which is exclusive of one line, and is aligned with the snap start triple double quotation marks. In addition, a function defined by the code ② does not have a document comment because the function is private to the module, and by its name _bytes_from_decode_data it is private, and the underscore function is private to the module.
Code comments
Working with document annotations in program code also involves adding code comments in key places, where the documentation comments are usually for someone who doesn't see the source code, and the code comments are for those who read the source code. Code comments typically take a single-line comment and a multiline comment.
The sample code is as follows:
# Base32 encoding/decoding must be do in Python①_b32alphabet = B ' ABCDEFGHIJKLMNOPQRSTUVWXYZ234567 ' _B32TAB2 = None_b 32rev = Nonedef B32encode (s): "" "Encode the Bytes-like object s using Base32 and return a bytes object. "" "Global _B32TAB2 # Delay The initialization of the table to not waste memory②# if the function is never Called③if _b32tab2 is None:b32tab = [bytes ((i,)) ' For I ' _b32alphabet] _b32tab2 = [A + b for a in B32tab for B in b32tab] B32tab = None if not isinstance (S, bytes_types): s = Memoryview (s). Tobytes () leftover = Len (s)% 5 # Pad The last quantum with zero bits if necessary④if leftover:s = s + B ' + ' * ( 5-leftover) # Don ' t use + =! encoded = ByteArray () from_bytes = int.from_bytes B32tab2 = _b32tab2 for I in range (0, Len (s), 5): c = Fro M_bytes (S[i:i + 5], ' big ') encoded + = (b32tab2[c >> +) + # bits 1–10⑤b 32tab2[(c >>) & 0X3FF] + # bits 11-20 b32tab2[(c >> Ten) & 0X3FF] + # bits 21- B32tab2[c & 0X3FF] # bits 31-40) # Adjust for any leftover par Tial quanta if leftover = = 1:encoded[-6:] = B ' ====== ' elif leftover = = 2:encoded[-4:] = b ' = = = ' E Lif leftover = = 3:encoded[-3:] = b ' = = = ' elif leftover = = 4:encoded[-1:] = B ' = ' return bytes (encoded)
The preceding code, line ② \~, ④ line, is a single-line comment that requires the same indentation level as the code that follows. Code ① line \~ line ③ is a multiline comment, and the comment requires the same indentation level as the code that follows it. The code ⑤ line is the end of the comment, which requires a very short comment content, there should be enough white space (at least two spaces) to separate the code and comments.
Using TODO comments
The IDE tools such as Pycharm provide some special comments for the source code, which is to add some identification to the code so that the IDE tool can quickly locate the code, which is one of the TODO comments. Todo annotations are not officially provided by Python, but the mainstream IDE tools also support TODO annotations. Todo comments describe the tasks that are pending here, or the code is not written to completion.
The sample code is as follows:
import com.pkg2.hello as module1from com.pkg2.hello import zy = 20# TODO 声明函数 print(y) # 访问当前模块变量yprint(module1.y) # 访问com.pkg2.hello模块变量yprint(z) # 访问com.pkg2.hello模块变量z
These comments are viewed in the Todo view of the Pycharm tool, and if you do not open the Todo view, you can place the mouse in the lower-left corner of the Pycharm
button, 5-1 shows the popup menu, select Todo, open the Todo view shown in 5-2, click on Todo to jump to the comment.
Import specification
The import statement is always placed at the top of the file, after the module comments and document comments, before the module global variables and constants. Each import statement can import only one module, the sample code is as follows.
Recommended:
import reimport structimport binascii
Not recommended:
import re, struct, binascii
However, there are multiple code elements behind the from import.
from codeop import CommandCompiler, compile_command
Import statements should be grouped from generic to Special order: standard library → third party library → own module, each group has a blank line, and the modules in the group are sorted in English dictionary order.
import io ①import osimport pkgutilimport platformimport reimport sysimport time ②from html import unescape ③from com.pkg1 import example ④
The above code in the import statement is divided into three groups, the Code ① line \~ ② line is the standard library module, note that its import order is orderly. The code line ③ is the module that is imported into the third-party library, and the code, ④, imports its own module.
Code layout
Code layout includes blank lines, spaces, line breaks, indents, and so on. Code layout content is more, the workload is very large, but also very important.
Blank Line
Blank lines are used to separate logically related code snippets to improve readability. The following is a specification that uses blank lines.
- The import statement block retains two blank lines before and after the sample code, where ①② and ③④ are two blank lines.
# Copyright 2007 Google, Inc. All Rights Reserved.# Licensed to PSF under a Contributor Agreement.
"" "Abstract Base Classes (ABCs) according to PEP 3119." ""
①
Ii
From _weakrefset import WeakSet
③
④
2. 函数声明之前保留两个空行,示例代码如下,其中①②处处是两个空行。```pythonfrom _weakrefset import WeakSet ①②def abstractmethod(funcobj): funcobj.__isabstractmethod__ = True return funcobj
The class declaration retains two blank lines, the sample code is as follows, where ①② is two blank lines.
①②class abstractclassmethod(classmethod):__isabstractmethod__ = Truedef __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable)
- A blank line is reserved before the method declaration, and the sample code is as follows, where ① is a blank line.
class abstractclassmethod(classmethod):__isabstractmethod__ = True①def __init__(self, callable):callable.__isabstractmethod__ = Truesuper().__init__(callable)
- There should be a blank line between the two logical blocks, as shown in the example code, where ① is a blank line.
def convert_timestamp(val):datepart, timepart = val.split(b" ")year, month, day = map(int, datepart.split(b"-"))timepart_full = timepart.split(b".")hours, minutes, seconds = map(int, timepart_full[0].split(b":"))if len(timepart_full) == 2: microseconds = int(‘{:0<6.6}‘.format(timepart_full[1].decode()))else: microseconds = 0①val = datetime.datetime(year, month, day, hours, minutes, seconds, microseconds)return val
Space
There are some places in the code that need spaces, and this is a lot of work. The following is a specification that uses spaces.
- There is a space before and after the assignment symbol "=".
a = 10c = 10
- All of the two-dollar operators should be separated by a space and the operand.
a += c + d
- Unary operator: The algorithm operator takes the inverse "-" and the operator to take the inverse "\~".
b = 10a = -by = \~b
- There are no spaces in parentheses, and the python brackets include parentheses "()", "brackets" [], and curly braces "{}".
Recommended:
doque(cat[1], {dogs: 2}, [])
Not recommended:
doque(cat[ 1 ], { dogs: 2 }, [ ])
5.
Do not precede commas, semicolons, and colons with spaces, but have a space behind them, unless the symbol is already at the end of the line.
Recommended:
if x == 88: print x, yx, y = y, x
Not recommended:
if x == 88 : print x , yx , y = y , x
- There should be no spaces before the opening parenthesis of the argument list, index, or slice.
Recommended:
doque(1)dogs[‘key‘] = list[index]
Not recommended:
doque (1)dict [‘key‘] = list [index]
Indent in
4 spaces are often used as a level of indentation. Although programmers can use tabs to indent at development time, and by default a tab is equal to 8 spaces, a tab and a space in different IDE tools will have a different number, so do not use tab indentation.
The contents of the code block are indented one level (4 spaces) relative to the first line, as shown in the following example:
class abstractclassmethod(classmethod): __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable)def __new__(mcls, name, bases, namespace, **kwargs): cls = super().__new__(mcls, name, bases, namespace, **kwargs) for base in bases: for name in getattr(base, "__abstractmethods__", set()): value = getattr(cls, name, None) if getattr(value, "__isabstractmethod__", False): abstracts.add(name) cls.__abstractmethods__ = frozenset(abstracts) return cls
Break
Up to 79 characters in a line of code. For document comments and multiline comments, a line is up to 72 characters long, but how to include a URL address in a comment is not subject to this limitation. Otherwise, if a break is required, it can be broken according to the following general specification:
- Break behind a comma.
bar = long_function_name(name1, name2, name3, name4)def long_function_name(var_one, var_two, var_three, var_four):
- Break in front of the operator.
name1 = name2 * (name3 + name4 - name5) + 4 * name6
Try not to use the continuation character (\), when the parentheses (including: curly braces, brackets, and parentheses) break open in parentheses, so that you do not use a continuation character.
def long_function_name(var_one, var_two, var_three, var_four):return var_one + var_two + var_three \ ① + var_four
name1 = name2 * (Name3 + name4
Bar = Long_function_name (name1, name2,
Name3, Name4)
Foo = {
Long_dictionary_key:name1 + name2
c = list[name2 * Name3
- Name4-name5 + 4 * Name6]
上述代码第①行使用了续航符进行断行,其他的断行都是在括号中实现的,所以省略了续行符。有时为了省略续行符,会将表达式用小括号包裹起来,如下代码所示:```pythondef long_function_name(var_one, var_two, var_three, var_four):return (var_one + var_two + var_three + var_four)
Tips
In Python, the backslash (\) can be used as a continuation character, telling the interpreter that the current line and the next line are joined together. However, if the continuation is implicit in curly braces, brackets, and parentheses.
Summary of this chapter
Through the study of the content of this chapter, the reader can understand the Python coding specifications, including naming specifications, annotation specifications, import specifications and code layout and other content.
Companion video
Http://edu.51cto.com/topic/1507.html
Supporting source code
Http://www.zhijieketang.com/group/8
Ebook
Https://yuedu.baidu.com/ebook/5823871e59fafab069dc5022aaea998fcc2240fc
Author Micro-blog: @tony_ dongsheng br/> Email:[email protected]
Python Reader service QQ Group: 628808216
Python from small white to Daniel 5th Python coding specification