python項目無用代碼檢查
需求總是在變化,代碼總是在修改,項目總是在重構,如果你不認真維護自己的項目,讓糟糕的代碼積累的越來越多,遲早有一天會積重難返。修改代碼或者重構過程中,經常會出現這樣的情況,一些函數已經不再使用了,但是出于某種原因,這些代碼沒有被删除,而是被保留了下來。随着時間的積累,這樣的代碼會原來越多,這為後來的人維護代碼造成了不必要的麻煩,是以,你需要經常清理那些無用的代碼。
說起來簡單,做起來卻不容易,從一個大的項目裡找出明确不再使用的函數并不是一件容易的事情,好在萬能的開源社群提供了一款第三方工具---dead, 使用pip來安裝
pip install dead
這個工具需要配合git來使用,它首先使用git ls-files指令來擷取所有的檔案,然後逐一進行檢查,将每一個檔案編譯成位元組碼,尋找定義和引用,如果最終找不到引用,就會給出提示
[email protected]:~/kwsy/coolpython$ dead
chapter is never read, defined in app.py:31
html is never read, defined in app.py:31
chapter is never read, defined in app.py:42
html is never read, defined in app.py:42
index is never read, defined in app.py:17
python_primary_tutorial is never read, defined in app.py:23
python_primary is never read, defined in app.py:29
python_senior_index is never read, defined in app.py:35
python_senior is never read, defined in app.py:40
filter is never read, defined in common/log.py:39
category is never read, defined in demo.py:2
fly is never read, defined in demo.py:7
PRIMARY is never read, defined in utils/generate_html.py:8
這是在我自己項目裡實驗的結果,那些隻有定義卻沒有被調用執行的函數都會被檢查出來,雖然大部分都是正常的代碼。
據作者自己所言,他是在飛機上畫了15分鐘完成的這個項目,好吧,老外就是牛逼。它還不是一個完美的項目,個别時候還會出現誤報,但是那些真正的隻有定義而沒有調用的函數都會被檢查出來,這樣可以幫助你尋找項目裡的死代碼。