python coding standards from PEP8
寫在前面
??A Foolish Consistency is the Hobgoblin of Little Minds!
??盡信書,則不如無書!這是從pep8規(guī)范上摘抄下來的話,正如代碼規(guī)范是為了提升代碼閱讀和編碼質量一樣,任何規(guī)范的首要原則就是一致性。我們應該遵循已經存在了的項目代碼風格,而不要為了規(guī)范而特意打破原來的平衡,當然如果你重頭開始一個新的項目,那么最好使用這些約定來幫助你和他人更好的理解和閱讀代碼。
一行代碼學習完所有規(guī)范
>>>pip install flake8 # or
>>>pip install pylint
??最好的學習方式就是安裝上述代碼規(guī)范檢查工具,當然并不限于以上兩種,這類的規(guī)范工具很多,選擇一種適合自己的且只安裝一種,因為它們之間也會為了某些標準而打架。當然如果你并不滿意或者不需要某種規(guī)范,可以按照下載工具的官方文檔去設置忽略它們,畢竟自己碼代碼碼的開心才最重要!
還是要學習如何寫
??盡管我們可以安裝工具來規(guī)范自己,時刻提醒自己,但不學習如何規(guī)范的編寫,到時候滿屏的波浪線會讓你崩潰。下面是我自己總結的一些基礎的編碼風格和規(guī)范,我會按照編寫一個py文件的順序來介紹。
一個固定的開頭
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""My favorite way.
first line: use absolute path of python.
second line: appoint the encode of file.
"""
#!/usr/bin/env python
"""Another way.
use env path better than the way above.
"""
#!/usr/bin/python2
"""python2!"""
#!/usr/bin/python3
"""python3!"""
# coding: utf-8
# coding=utf-8
"""A short way.
but I don't think it beautiful than my way just in format.
"""
??正如你所看到那樣,僅僅開頭就花樣百出。但我仍然沒有列出所有的方式,你也不必糾結有多少種寫法,選擇一種你最喜歡的方式足以。
??那么為啥要寫這兩行呢?
-
#!/usr/bin/python
??指定所用的python解釋器,python后面的數字指定python版本;當然這行代碼在windows下意義不大,主要是針對linux/unix用戶,如果在linux/unix下加上這行代碼,并且當前用戶對py文件擁有可執(zhí)行權限的話,可以在終端直接輸入./filename.py
執(zhí)行py文件(驗證時請注意使用ls?-all查看權限,有時root也不一定擁有可執(zhí)行權限,使用chmod進行修改即可驗證)。不加這行代碼或者當前用戶沒有權限,則使用python filename.py
執(zhí)行。 -
-*- coding: utf-8 -*-
??指定文件編碼,這個主要是針對python2的py文件中如果出現(xiàn)非ASCII
字符會報錯,即使是在注釋中;而python3默認utf-8
編碼,可以不加此行代碼,但為了代碼的可移植性,請務必添加。
規(guī)范使用import
import sys # first import the standard library
# put a blank line
import requests # then import the third party
# put a blank line
import my_module # finally use own module
import os, sys # don't use this, separate them in different line
# import like this
import os
import sys
# this is ok
from subprocess import Popen, PIPE
# try not use this as possible as you can
from os import *
開始正式碼代碼
- 代碼編排
1 import os
2
3
4 # put two blank lines
5 class CodeStyle:
6
7 def use_four_space_for_indent(self):
8 """Four space for indent."""
9 pass
10
11 def put_one_blank_line(self):
12 """One blank line between the class method."""
13 pass
14
15
16 def alone_function():
17 """Get two blank lines between the class."""
18 pass
19
20
21 if __name__ == '__main__':
22 """Also two lines."""
23 print('the last line!') # put a blank line in the last, like code line mark number 24
24
- 命名規(guī)范
# use some meaningful words
import my_module # lowercase, use underscore
THE_CONSTANT_NAME = 1 # uppercase, use underscore
class MyClass: # CapWords
def __init__(self):
self.the_class_attr = 1 # lowercase, use underscore
def class_method_name(self): # lowercase, use underscore
pass
def the_function_name(param_name): # lowercase, use underscore
the_variable_name = 1 # lowercase, use underscore
- 有趣的空格
# use like this
x = 1
y = 1
long_variable = 3
# don't
x = 1
y = 1
long_variable = 3
# no space between '=', but still has one space in parameters
def function1(param1, param2, param3=3):
return function2(param1=1, param2=2)
# some more examples
# yes
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
# No
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
# Yes
if foo == 'hehe':
return True
for i in list:
x += i
while True:
do_this()
# No
if foo == 'hehe': return True
for i in list: x += i
while True: do_this()
# comment
# there has one space after '#'
- 文檔和注釋
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Module document.
use """ """, write something important.
first line first word in document uppercase.
the module document before import statement,
like this.
"""
import my_module
class MyClass:
"""MyClass document, single line."""
# or
"""MyClass document.
multi-line.
and many words.
and...
"""
def __init__(self):
"""Init the object."""
pass
def function(param1, param2):
"""
This is a groups style docs from google.
Parameters:
param1 - this is the first param
param2 - this is a second param
Returns:
This is a description of what is returned
Raises:
KeyError - raises an exception
"""
pass
# and this is a single comment, notice the space after '#'
# we should use English comment as possible as we can.
# it can improve our language sense, so you can see it
# why I try to write so many poor English comments and
# I'm just kidding. that's advice from pep8, but we
# should follow our project language that the most people
# can accept it. notice use two space after a
# sentence-ending period in multi-sentence comments,
# except the last one.
#
# the best way to write comment is don't use two language
# in comments!
編碼結束
??have fun in python!