無論是接手同事的祖?zhèn)鞔a還是學習優(yōu)秀開源項目絮蒿,都需要閱讀代碼僵朗,簡單粗暴的 vim foo.py
當然可以壤蚜,但更好的方式是提前做好充足的準備转绷,下面是我日常的一些技巧:
1.格式化代碼
每個人的編程風格迥異,不一定符合 pep8規(guī)范戈毒,閱讀前先將代碼格式化能夠帶來賞心悅目的閱讀體驗艰猬;如下是一坨代碼風格很差的代碼:
import math, sys;
def example1():
####This is a long comment. This should be wrapped to fit within 72 characters.
some_tuple=( 1,2, 3,'a' );
some_variable={'long':'Long code lines should be wrapped within 79 characters.',
'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
20,300,40000,500000000,60000000000000000]}}
return (some_tuple, some_variable)
def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key(''));
class Example3( object ):
def __init__ ( self, bar ):
#Comments should have a space after the hash.
if bar : bar+=1; bar=bar* bar ; return bar
else:
some_string = """
Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
return (sys.path, some_string)
格式化后
import math
import sys
def example1():
# This is a long comment. This should be wrapped to fit within 72
# characters.
some_tuple = (1, 2, 3, 'a')
some_variable = {
'long': 'Long code lines should be wrapped within 79 characters.',
'other': [
math.pi,
100,
200,
300,
9876543210,
'This is a long string that goes on'],
'more': {
'inner': 'This whole logical line should be wrapped.',
some_tuple: [
1,
20,
300,
40000,
500000000,
60000000000000000]}}
return (some_tuple, some_variable)
def example2():
return ('' in {'f': 2}) in {'has_key() is deprecated': True}
class Example3(object):
def __init__(self, bar):
# Comments should have a space after the hash.
if bar:
bar += 1
bar = bar * bar
return bar
else:
some_string = """
Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
return (sys.path, some_string)
賞心悅目多了吧~
社區(qū)有很多格式化工具,如:pylint埋市、yapf冠桃、autopep8等
2.自動生成類型注解
靜態(tài)語言更易后期團隊維護的一個原因是變量定義時就指定了類型,Python 3.6之后類型注解功能稍微補足了這方面道宅;而Facebook 的Instagram 團隊開源的 MonkeyType 這個工具能對現(xiàn)有的代碼自動生成類型注解食听,是個大神器~
一個普通不過的函數(shù)定義
def add(a, b):
return a + b
自動生成類型注解后
def add(a: int, b: int) -> int:
return a + b
3.靜態(tài)檢查
有了類型注解后就可以在不運行程序的情況下進行靜態(tài)檢查及時發(fā)現(xiàn)錯誤了,譬如下面這段程序, fib 函數(shù)應該接受整型污茵,但不小心傳了字符串:
from typing import Iterator
def fib(n: int) -> Iterator[int]:
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
print(fib('4'))
運行靜態(tài)檢查工具 mypy 就可以提前發(fā)現(xiàn)錯誤了:
4.找一個好的代碼閱讀器
這方面好的編輯器就已經(jīng)是非常優(yōu)秀的閱讀器了樱报,代碼高亮、定義跳轉等都是標配了泞当;
SpaceVim迹蛤、VS Code、PyCharm襟士、Sublime Text都是業(yè)內有口皆碑的產(chǎn)品
5.更美觀的異常提示
代碼運行可能會報異常盗飒,better-exceptions這個工具能產(chǎn)生比默認更美觀的異常提示:
6.官方手冊隨身帶
閱讀代碼過程中可能遇到個自己不太熟悉函數(shù)名或語法,這時候再谷歌就太沒效率了陋桂,Alfred+Dash(或 devdocs)能將官方手冊隨時調用出來查詢