今天要介紹的是 PEP 8,這是 Python 社群普遍採用的 coding style,今天重點介紹幾個內容,讓我們的 code 更具一致性與可讀性。
# Correct:
import os
import sys
# Wrong:
import sys, os
# Correct:
from subprocess import Popen, PIPE
雖然 PEP 8 沒有特別提到,但同一組之間通常會用字母排序,以前一天test.py
的開頭舉例。
import json
import os
import time
from dotenv import load_dotenv
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from pages.article_page import ArticlePage
from pages.ithelp_page import ITHelpPage
from pages.login_page import LoginPage
# Correct:
spam(ham[1], {eggs: 2})
# Wrong:
spam( ham[ 1 ], { eggs: 2 } )
# Correct:
foo = (0,)
# Wrong:
bar = (0, )
# Correct:
if x == 4: print(x, y); x, y = y, x
# Wrong:
if x == 4 : print(x , y) ; x , y = y , x
# Correct:
spam(1)
# Wrong:
spam (1)
# Correct:
dct['key'] = lst[index]
# Wrong:
dct ['key'] = lst [index]
# Correct:
x = 1
y = 2
long_variable = 3
# Wrong:
x = 1
y = 2
long_variable = 3
=, +=, >, and
)# Correct:
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
# Wrong:
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
# Correct:
def complex(real, imag=0.0):
return magic(r=real, i=imag)
# Wrong:
def complex(real, imag = 0.0):
return magic(r = real, i = imag)
通常分為以下幾種
b
python (單一小寫字母)B
python (單一大寫字母)lowercase
python(小寫字母)lower_case_with_underscores
python(帶底線小寫字母)UPPERCASE
python(大寫字母)UPPER_CASE_WITH_UNDERSCORES
python(帶底線大寫字母)CapitalizedWords
python (駝峰式命名)b
python (單一小寫字母)lowercase
python(小寫字母)lower_case_with_underscores
python(帶底線小寫字母)
CapitalizedWords
python (駝峰式命名)
Package:lowercase
python(小寫字母)
(不鼓勵帶底線)
Module:lowercase
python(小寫字母)lower_case_with_underscores
python(帶底線小寫字母)
UPPERCASE
python(大寫字母)UPPER_CASE_WITH_UNDERSCORES
python(帶底線大寫字母)
關於 PEP 8 的部分就介紹到這裡,原文件還有介紹很多規範,有興趣的人可以參考: PEP 8 – Style Guide for Python Code(也是今天的參考資料)
明天預計會介紹 Version Coltrol(版本控制),以及使用 Github 的方法