Python: code specification and naming specification

Machine vision 001 2020-11-13 02:49:36
python code specification naming specification


Python: Code specification and naming convention

All nomenclature rules must abide by these three rules :

1. Names can only be given in letters or _ Start with an underline ;

2. Names cannot contain spaces ;

3. Name cannot overlap with keyword . You can't put the character l( Lowercase letters l),'O''o'( Case letters o)、'I'( Capital I) Used as variable name , Prevention and digital 0、1 confusion .

 

modular

Modules should be named in lowercase as much as possible , Keep the initials in lowercase , Try not to underline ( Except for multiple words , And a small number of cases ).

# Correct module name
import decoder
import html_decoder
# Module name not recommended
import Decoder

 

Class name

Class names use humps (CamelCase) Naming style , title case , Private classes can start with an underscore .

class Farm():
pass
class AnimalFarm(Farm):
pass
class _PrivateFarm(Farm):
pass

Put related classes and top-level functions in the same module . Unlike Java, There's no need to limit a class to a module .

 

function

All function names are lowercase , If there are more than one word , Separate... With underscores .

def func():
pass
def func_with_env():
pass

Private functions place an underline before the function _.

class Person():
def _private_func():
pass

 

Variable

Try to lower the variable name , If there are more than one word , Separate... With underscores .

Private class members are identified with a single underscore prefix .

Variable names should not have type information , Such as num_list,ani_dict etc. .

if __name__ == '__main__':
count = 0
your_name = ''

 

Constant

Constants are in uppercase , If there are more than one word , Use an underline to separate .

MAX_CLIENT = 100
MAX_CONNECTION = 1000
CONNECTION_TIMEOUT = 600

abnormal ExceptionName

With Error As a suffix :

try:
pass
except ValueError as result:
pass

The leading suffix underline indicates

  • A leading underline : Non public
  • One suffix underline : Avoid keyword conflicts
  • Two leading underscores : Use when naming a class property causes name conflicts
  • Two leading and suffix underscores : An object or property that has a special purpose , for example __init__ and __str__

 

code

  • In the absence of special circumstances , All documents are in use UTF-8 code ;
  • In the absence of special circumstances , The header of the file must be added with #-*-coding:utf-8-*- identification .

 

Code format

Indent

Unified use 4 Space to indent

Line width

Try not to exceed... Per line of code 80 Characters ( In special cases, it can be slightly more than 80 , But not more than 120).

reason :

  • This is looking at side-by-side Of diff It's very helpful
  • Easy to view code under the console
  • Too long may be a design defect

quotes

In short , Natural language use “ Double quotes ”, The machine label uses “ Single quotation marks ”, So most of the code should use “ Single quotation marks ”.

  • Natural language : Use double quotes  "..."
    E.g. error message ; A lot of things are still unicode, Use u" Hello world "
  • Machine identification : Use single quotes  '...'
    for example dict Inside key
  • Regular expressions : Use native double quotes  r"..."
  • docstring (docstring)  Use three double quotes  """......"""

Blank line

  • There are two empty lines between module level functions and class definitions ;
  • Empty line between class member functions ;
  • Multiple empty lines can be used to separate groups of related functions
  • Function can use empty lines to separate out logically related code
class Class:
def __init__(self):
pass
def hello(self):
pass
def main():
pass 

 

import sentence

import Sentences should be written separately :

# Correct writing
import os
import sys
# It's not recommended
import sys,os
# Correct writing
from subprocess import Popen, PIPE

import The sentence should use  absolute import

# Correct writing
from foo.bar import Bar
# It's not recommended
from ..bar import Bar
  • import The statement should be placed in the head of the file , Module description and docstring after , Before global variables ;
  • import Sentences should be arranged in order , Each group is separated by a blank line
import os
import sys
import msgpack
import zmq
import foo

When importing class definitions of other modules , You can use relative import

from myclass import MyClass

If there is a naming conflict , You can use the namespace

import bar
import foo.bar
bar.Bar()
foo.bar.Bar()

 

Space

One space on each side of a binary operator [=,-,+=,==,>,in,is not, and]

# Correct writing
i = i + 1
submitted += 1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
# It's not recommended
i=i+1
submitted +=1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

Function's argument list ,, There should be a space after :

# Correct writing
def complex(real, imag):
pass
# It's not recommended
def complex(real,imag):
pass

Function's argument list , The default value is equal sign without spaces :

# Correct writing
def complex(real, imag=0.0):
pass
# It's not recommended
def complex(real, imag = 0.0):
pass

After the left bracket , Don't add extra space before the right bracket :

# Correct writing
spam(ham[1], {eggs: 2})
# It's not recommended
spam( ham[1], { eggs : 2 } )

Don't leave extra space before the left bracket of the dictionary object :

# Correct writing
dict['key'] = list[index]
# It's not recommended
dict ['key'] = list [index]

Do not use extra spaces for alignment assignment statements :

# Correct writing
x = 1
y = 2
long_variable = 3
# It's not recommended
x = 1
y = 2
long_variable = 3

 

Line break

Python Support line breaks in brackets . There are two scenarios .

1) The second line is indented to the beginning of the bracket :

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

2) The second line is indented 4 A space , Applicable to the case where the starting bracket is wrapped :

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

Use backslash \ Line break , Binary operator + . Wait should appear at the end of the line ; Long strings can also be wrapped in this way :

session.query(MyTable).\
filter_by(id=1).\
one()
print 'Hello, '\
'%s %s!' %\
('Harry', 'Potter')

Compound statements are forbidden , That is, a line contains multiple statements :

# Correct writing
do_first()
do_second()
do_third()
# It's not recommended
do_first();do_second();do_third();

if/for/while Be sure to change lines :

# Correct writing
if foo == 'blah':
do_blah_thing()
# It's not recommended
if foo == 'blah': do_blash_thing()

 

docstring

docstring The most fundamental two points in the specification of :

  1. All the common modules 、 function 、 class 、 Method , It should be written docstring . Private methods don't have to be , But it should be in def A block comment is provided to illustrate .
  2. docstring The end of """ Should have a monopoly on , Unless docstring There is only one line .
"""Return a foobar
Optional plotz says to frobnicate the bizbaz first.
"""
"""Oneline docstring"""

notes

Block annotation

“#” There is a space after the number one , Paragraphs are separated by blank lines ( Also need to “#” Number ):

# Block annotation
# Block annotation
#
# Block annotation
# Block annotation 

Line notes

Use at least two spaces to separate the statement , Be careful not to use meaningless comments :

# Correct writing
x = x + 1 # The border is bold by one pixel
# It's not recommended ( Meaningless notes )
x = x + 1 # x Add 1

Suggest

  • In the key part of the code ( Or something more complicated ), Those who can write notes should write notes as much as possible ;

  • The more important comment section , Use multiple equal signs to separate , Can be more eye-catching , Highlight the importance of .
app = create_app(name, options)
# =====================================
# Do not add... Here get post etc. app Routing behavior !!!
# =====================================
if __name__ == '__main__':
app.run()

Documentation Comments (Docstring)

As a document Docstring It usually appears in the module head 、 Function and class headers , In this way python Can be passed through the object __doc__ Object to get the document .
Editor and IDE It can also be based on Docstring Give an automatic prompt .

  • Document notes to """ The beginning and the end , The first line doesn't wrap , If there are many lines , The last line must wrap , Here are Google Of docstring Style example :
# -*- coding: utf-8 -*-
"""Example docstrings.
This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.
Example:
Examples can be given using either the ``Example`` or ``Examples``
sections. Sections support any reStructuredText formatting, including
literal blocks::
$ python example_google.py
Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.
"""

Do not copy the function definition prototype in the document comments , It's a concrete description of its content , Explain specific parameters and return values, etc :

# It's not recommended ( Don't write function prototypes and so on )
def function(a, b):
"""function(a, b) -> list"""
... ...
# Correct writing
def function(a, b):
""" Calculate and return a To b The average of the data in the range """
... ...

For function parameters 、 The description of return value, etc numpy standard , As shown below :

def func(arg1, arg2):
""" Here is a sentence summary of the function ( Such as : Calculate average ).
Here is a detailed description of .
Parameters
----------
arg1 : int
arg1 Specific description of
arg2 : int
arg2 Specific description of
Return value
-------
int
Specific description of the return value
see
--------
otherfunc : Other correlation functions, etc ...
Example
--------
Example use doctest Format , stay `>>>` After the code can be automatically run by the document test tool as a test case
>>> a=[1,2,3]
>>> print [x + 3 for x in a]
[4, 5, 6]
"""
  • Document notes are not limited to Chinese and English , But don't mix Chinese and English ;

  • The longer the document comment, the better , Usually one or two sentences can make the situation clear ;

  • modular 、 Public class 、 Public methods , Be able to write notes on documents , You should try to write document notes .

 

 

 

 

 

 

 

 

 

 

 

 

 

 

版权声明
本文为[Machine vision 001]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database