慣例與 PEP 8

Python 的軟體工程原則

Adam Spannbauer

Machine Learning Engineer at Eastman

什麼是慣例?

碰拳

鞠躬的人

握手

Python 標誌

Python 的軟體工程原則

認識 PEP 8

PEP 8

「程式碼被閱讀的次數遠多於被撰寫」

Python 的軟體工程原則

違反 PEP 8

#define our data
my_dict ={
    'a'  : 10,
'b': 3,
    'c'  :   4,
             'd': 7}
#import needed package
import numpy as np
#helper function
def DictToArray(d):
    """Convert dictionary values to numpy array"""
    #extract values and convert
              x=np.array(d.values())
              return x
print(DictToArray(my_dict))
array([10,  4,  3,  7])
Python 的軟體工程原則

遵守 PEP 8

# Import needed package
import numpy as np

# Define our data
my_dict = {'a': 10, 'b': 3, 'c': 4, 'd': 7}


# Helper function
def dict_to_array(d):
    """Convert dictionary values to numpy array"""
    # Extract values and convert
    x = np.array(d.values())
    return x


print(dict_to_array(my_dict))
array([10,  4,  3,  7])
Python 的軟體工程原則

PEP 8 工具

PEP 8 與 PyCharm

pycodestyle 套件

Python 的軟體工程原則

使用 pycodestyle

datacamp@server:~$ pip install pycodestyle
datacamp@server:~$ pycodestyle dict_to_array.py
dict_to_array.py:5:9: E203 whitespace before ':'
dict_to_array.py:6:14: E131 continuation line unaligned for hanging indent
dict_to_array.py:8:1: E265 block comment should start with '# '
dict_to_array.py:9:1: E402 module level import not at top of file
dict_to_array.py:11:1: E302 expected 2 blank lines, found 0
dict_to_array.py:13:15: E111 indentation is not a multiple of four
Python 的軟體工程原則

pycodestyle 的輸出

pycodestyle 錯誤輸出

Python 的軟體工程原則

一起來練習吧!

Python 的軟體工程原則

Preparing Video For Download...