Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

程式可以優化的方向 #289

Open
danny0838 opened this issue May 29, 2024 · 0 comments
Open

程式可以優化的方向 #289

danny0838 opened this issue May 29, 2024 · 0 comments

Comments

@danny0838
Copy link

danny0838 commented May 29, 2024

1. 可以考慮用 flake8 等工具把 Python 程式碼格式統一(一般建議盡量以 PEP 8 為主),比較整齊。未來貢獻者也比較知道要貢獻程式碼時怎麼撰寫。

個人習慣安裝的規則集,供參:

flake8 >= 4.0
pep8-naming >= 0.13.2
flake8-comprehensions >= 3.7
flake8-string-format >= 0.3
flake8-quotes >= 3.4
flake8-bugbear >= 22.0
flake8-isort >= 4.2
isort >= 5.5

安裝後在根目錄執行 flake8 scripts 就會自動檢查語法有問題的程式碼。規則設定檔可寫在 .flake8

上述這段可以寫成 requirements.txt 檔案放根目錄或 scripts 目錄下,之後要開發程式時可用 pip install -r requirements.txt 快速安裝相同的依賴套件。

2. 一般程式內部不建議使用 exit(),通常是 raise error 夾帶錯誤資訊給上一層處理,然後在頂層用 try ... except 統一做錯誤處理。命令列程式出錯通常會回傳非 0 數,通常是 print 錯誤訊息到 stderr 再用 sys.exit(1) 中止程式。

3. 要支援複雜一點的程式執行訊息可考慮用 logging 模組

我個人是習慣先這樣設定:

logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
log = logging.getLogger(__name__)

之後程式就用 log.infolog.warninglog.errorlog.criticallog.debug 輸出執行細節。一般可在 command 加上 -q 參數略過 log.info 的一般訊息及 -v 參數輸出 log.debug 的除錯用訊息。

不過 logging 通常是輸出到 stderr,和輸出到 stdout 的 print 不太一樣。

4. 文字模版用一堆 xxx + yyy 有點醜,通常會把模版文字統一寫在常數(或另一個 script 裡再匯入) TPL_XXX = """... {argname} ...""" 之後用 str.format() 帶入變數內容(還可以做數字格式處理等),或直接寫成 f-string 帶入前面的變數內容: xxx = f"""... {argname} ...

比較大的程式用 """ 的時候,第二行以後都無縮排,會比較亂,可考慮用 textwrap.dedent 讓多行文字和程式碼一起縮排:

text = dedent(
    """\
    xxx
    yyy
    ...
    """
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant