current position:Home>Python programming specification

Python programming specification

2022-07-24 18:16:29Full stack programmer webmaster

Hello everyone , I meet you again , I'm your friend, Quan Jun .

1,Python Programming specification

> code

 be-all  Python  Script files should be marked with 


# -*- coding:utf-8 -*-
 Used to set the editor , Save as by default  utf-8  Format .

> notes

 The industry generally agrees that  Python  There are two types of comments ,

 One is by  #  At the beginning “ real ” notes , for example , It is used to indicate why the current implementation is selected and the principles and difficulties of this implementation 

 The other is  docstrings, for example , Used to show how to use this package 、 modular 、 class 、 function ( Method ), Even use examples and unit tests to adhere to the principle of appropriate annotation .

 Do not comment on the code without technical difficulties , The code with technical difficulties must be annotated . But unlike notes , It is recommended for each package 、 modular 、 class 、 function ( Method ) Write  

docstrings, Unless the code is clear at a glance , It's simple .

> Indent

Python  Rely on indentation to determine the level of code blocks , There are mainly two kinds of blank characters at the beginning of a line :tab  and   Space , However, it is strictly forbidden to mix the two . If you use  tab  Indent , Set up tab  by  4  A space .

> Space

Spaces in Python It makes sense in the code , because Python The syntax of depends on indentation , Spaces at the beginning of a line are called leading spaces . In this section, we will not discuss the content related to leading spaces , Only non leading spaces are discussed . Non leading spaces in Python There is no meaning in the code , But properly adding non leading spaces can improve the readability of the code .

1) In binary arithmetic 、 Add spaces before and after logical operators : Such as 

a = b + c;
2)  Do not add spaces after the unary prefix operator , Such as 

if !flg: pass;
3) “:” When used at the end of a line, there is no space before or after , Such as branching 、 loop 、 Function and class definition language ; Use it at the end of a non line with spaces at both ends , Such as :

dict  Object definition 

d = {'key' :  'value'}
4)  Brackets ( With parentheses 、 Square brackets and curly braces ) No spaces before and after , Such as :

do_something(arg1, arg2)
 instead of do_something( arg1, arg2 )

5)  Don't use commas 、 A semicolon 、 A colon is preceded by a space , But they should be followed by ( Except at the end of the line )

6)  Don't use spaces to align multiple lines vertically , Because it's going to be a maintenance burden ( Apply to :,#,= etc. )

> Blank line

Appropriate blank lines help to increase the readability of the code , Blank lines can refer to the following guidelines :

1)  In the class 、 Empty lines between the definitions of functions ;
2)  stay  import  Add blank lines between different types of modules ;
3)  Add blank lines between logical paragraphs in a function , That is to put the relevant code together , As a logical paragraph , Paragraphs are separated by blank lines ;

> Line breaks

Although the current widescreen display can display more than 256 Column characters , However, this specification still insists that the maximum length of the line shall not exceed 80 A standard of characters . There are several ways to fold long lines :

1) Change the long variable name to a short one , Such as :

this.is.a.very.long.variable_name = this.is.another.long.variable_name

Should be changed to :

variable_name1 = this.is.a.very.long.variable_name
variable_name2 = this.is.another.variable_name
variable_name1 = variable_name2s

2) Python Will put parentheses 、 The lines in brackets and curly brackets are connected implicitly , You can take advantage of this feature . If needed , You can add an extra pair of parentheses around the expression

3) Add a continuation character to the long line to forcibly break the line , The position of the line break should be before the operator , And one more indent after line feed , So that when the maintainer looks at the code, he can see the beginning of the code line and judge that there is line feed here , Such as :

if color == WHITE or color == BLACK \
    or color == BLUE: #  Be careful  or  The operator is at the beginning of the new line, not at the end of the old line 
do_something(color);

> character string

1. Avoid using in a loop + and += Operator to accumulate strings . Because strings are immutable , Doing so creates unnecessary temporary objects , And it leads to quadratic rather than linear run times .
 As an alternative , You can add each substring to the list , And then at the end of the loop, use  .join  Connection list .( You can also write one for each substring  cStringIO.StringIO  In cache 
2. Use triple double quotes instead of triple single quotes for multiline strings . But be careful ,  It's usually clearer to use implicit lines to connect , Because multiline strings don't indent with the rest of the program .

> name

 Consistent naming can save developers a lot of trouble , Proper naming can greatly improve the readability of the code , Reduce maintenance costs .

>> Constant

Constant names all uppercase , Connect words by underscores , Such as

WHITE = 0XFFFFFF
THIS_IS_A_CONSTANT = 1

>> Variable

Variable names are all lowercase , Connect words by underscores , Such as

color = WHITE
this_is_a_variable = 1

Private class members are identified with a single underscore prefix , Multiple definition public members , Define fewer private members .

Variable name should not have type information , because Python Is a dynamically typed language . Such as iValue、names_list、dict_obj Waiting is a bad name .

>> function

 The naming rules of function names are the same as variable names .

>> class

Use capital letters for class names ( Such as CapWords, namely Pascal style ), Do not use underscores to connect words . Such as :

class ThisIsAClass(object):pass

>> modular

Module names are all lowercase , For modules used in the package , You can add an underscore prefix , Such as

module.py
_internal_module.py

>> package

 The naming convention of the package is the same as that of the module 

>> abbreviation

Try to use the word spelled as much as possible , There are two abbreviations : 1) Common abbreviations , Such as XML、ID etc. , It should also be named with only uppercase initials , Such as

class XmlParser(object):pass

2) Long words in naming , Abbreviate a word . In this case, the contracted abbreviation should be used , Such as removing vowels 、 The first character containing consonants, etc , for example :

function  Abbreviation for  fn

text  Abbreviation for  txt

object  Abbreviation for  obj

count  Abbreviation for  cnt

number  Abbreviation for  num, etc. .

>> Specific nomenclature

Mainly refers to __xxx__ Systematic retention word nomenclature of form . This naming can also be used in projects , It means that variables in this form are read-only , Try not to overload this form of class member function . Such as

class Base(object):
    def __init__(self, id, parent =None):
        self.__id__ = id
        self.__parent__ = parent
    def __message__(self, msgid):
        # … A little 

among __id__、__parent__ and __message__ System reserved word nomenclature is adopted .

>> Import format

  1. import The order of the , First import Python Built-in module , Again import Third-party module , Last import Other modules in the self-developed project ; These modules are separated by blank lines .
  2. Every import Should have a monopoly on .
  3. Do not use from module import *, Unless it is import Constant definition modules or other modules that you ensure do not have namespace conflicts .

> assignment

For assignment language , The main thing is not to do unnecessary alignment , Such as :

a            = 1                               #  This is a line comment 
variable = 2                               #  Another line comment 
fn           = callback_function    #  Or comment 

There is no need to do this alignment , For two reasons : First, this alignment will disturb the attention of programming , The brain has to deal with two things at the same time ( Programming and alignment ); Second, it is difficult to read and maintain in the future , Because the horizontal field of vision of the human eye is very narrow , It is difficult to treat three fields as one line , And adding a longer variable name during maintenance will also break the alignment . It is better to write directly like this :

a = 1 #  This is a line comment  variable = 2 #  Another line comment  fn = callback_function #  Or comment  

> sentence

Usually, each statement should have a single line . however , If the test result and the test statement are on the same line , You can also put them on the same line . If it is if sentence , Only in the absence of else Only when you can do this . Specially , Never be right about try/except To do so , because try and except It can't be on the same line .

2, Reference material

3, Document modification history

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/124465.html Link to the original text :https://javaforall.cn

copyright notice
author[Full stack programmer webmaster],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/203/202207211150281795.html

Random recommended