紀錄了pep8 coding style, logging 以及 debugger的教學內容
Intro
最近開始使用了PyCharm,在邁向FullStack Data Scientist的路上勢必會遇到需要寫多個.py讓資料處理的pipeline穩定執行、特徵工程、模型部署……等趁著最近有時間,使用free-trial迅速的把Tree House — Write Better Python有系統地學起來放。
Pep8
- 講師推薦pep8以及pep20來遵守
- Top-level function → 兩行blank line區隔彼此
- Class → 兩行blank line區隔彼此
- Class中的function → 一行blank line區隔彼此
- 用空格或是Tab,但不要混用,造成編碼出錯時很難認出
- pep8在PyCharm中會給出hint
- jupyter nbextension中可以開啟Autopep8,會出現一個小錘子,點一下自動修好,這也很棒,PyCharm中也可以快捷鍵自動Autopep8
- function name使用小寫並且每個單字用底線隔開
- class name首字大寫
- 變數名稱除了計數器&迭代器之外,避免使用單個字母命名
- [延伸閱讀] 關於module_name, package_name, ……更多命名規則
*args
→ 將參數視為一個set,能夠一次餵進function中**args
→ 將參數視為一個dictionary,能夠一次餵進function中- final check可以使用flake8在終端機輸入,檢查.py檔案,會吐出coding style不好的地方,讓我們可以修改
- 除了flake8還有pylink可以用,pylink會檢查得更深更細
# multiple imports
# top level function (outside the class)
# should be two space to between them
# function name are generally lowcase and have an underscore between words def foo_bar(arg1, arg2, arg3, arg4):
return arg1, arg2, arg3, arg4
def bar(*args):
return 2 + 2
# Bad class name, bad spacing, bad indentation
# class with two space
# class with capital T
class Treehouse:
def one(self):
return 1 def two(self):
return 2
alpha, beta, charlie, delta = foo_bar("a long string",
"a longer string",
"yet another long string",
"and other crazy string") one = 1
three = 3
fourteen = 14 # make fourteen equal to 12 print(alpha)
print(fourteen)
print(Treehouse().two())
Logging
- 原本我們用print來了解程式發生什麼事,是時候用更專門的package,更有效率的追蹤
- 可以按照level來吐log → CRITICAL → ERROR → WARNING → INFO → DEBUG → NOTSET,從嚴重到不嚴重,如果選擇level為DEBUG,則層級在DEBUG之上的都會顯示
- 使用logging.basicConfig來加入到’game.log’當中,搭配.format抓取想要看的參數在程式中結果
- 延伸閱讀[Python中使用logging模組列印log日誌詳解]
- 延伸閱讀[ [Python] logging 教學 ]
import logginglogging.basicConfig(filename='game.log', level=logging.DEBUG)"""your code"""logging.info('x : {}; y : {}; z : {};'.format(variable_a, variable_b, variable_c)
Python Debugger (pdb)
- 從DS領域入門時,Kaggler常說,有print即可,但換到開發環境就很沒效率了
- 我們可以使用逐次print, 或是import pdb ; pdb.set_trace()
- pdb會在終端機執行python時,在trace的行數中停下,變成像是ipython般的互動shell,告訴你下一個動作他要做什麼,此時我們可以透過輸入變數名稱my_list檢查變數內容是否如我們所想
- 如果執行下一步,輸入next 或是 n,如果要執行後面全部的步驟,輸入continue或是c
- 這裡也前後呼應了pep8的coding style,不要使用單個字母作為變數名稱,在這裡就有可能和pdb中的n或c搞混
- 在使用pdb時,常見的coding style會直接寫在script中,所以如果看到import沒有在最上面也不用覺得太奇怪,然後除完bug就可以拿掉了
- [Linux commend] cat可以看文件內容, which可以取得path
my_list = [5, 2, 1, True, "abcdefg", 3, False, 4]
# a slower way to do it
# del my_list[3]
# print(my_list)
# del my_list[4]
# print(my_list)
# del my_list[6]
# print(my_list)# use pdb
# n for next, c for continue, type the variable name to check the variable
import pdb ; pdb.set_trace()
del my_list[3]
del my_list[3]
del my_list[4]