Effective python note chapter 10
第十章: Collaboration
Wiki topics:
📊 · Economic Policy
Effective python note chapter 10
第十章: **Collaboration

# Item 82: 知道如何去找到內建 modules 的社群
- Python package index (PyPI) 包含了許多由 python 社群開發且維護的 package
- pip 是一個 command line tool, 用來下載 PyPI 的 packages
- 主要的 PyPI modules 為免費且開源
# Item 83: 為了獨立及可重現相依性, 要使用虛擬環境
- 虛擬環境讓你可以在一台電腦上安裝同一個 package, 但是可以為不同版本的, 且不會有衝突
- 創建指令: python -m venv; enable 指令: source bin/activate; disabled 指令: deactivate
- 使用 python3 -m pip freeze 來 dump 出你的環境的 requirements, 當要重現你的環境時, 使用 python3 -m pip install -r requirememts.txt
# Item 84: 在每個 function, class, module 中寫 docstrings
- 維護好 docstrings, 特別是當程式有做修改時
- 對於 modules: 介紹此 module 有什麼重要的 class 或 function
- 對於 classes: 介紹行為, 特別的屬性或是 subclass 的行為
- 對於 function 及 methods: 介紹各個參數, 回傳的數值, raised exception 及 function 本身的行為
- 若是有使用 type annotations, 則在 docstrings 中可以忽略已經有的資訊
# Item 85: 使用 packages 來組織 modules 以及提供穩固的API
- Packages 允許你組織你的程式到獨特的絕對模塊名稱, 且沒有衝突的命名空間
- 新增一個 init.py 到資料夾中, 就可以定義自己的 packages
- 定義特別的屬性 all, 可以為 module 提供特定的 API
- 當與一個 team 合作或是只有一個 codebase 時, 就不需要為了特定的 API 使用 all
# Item 86: 考慮 module-scoped-code 來配置部署環境
- 程式通常會運行在不同環境中, 需要各自不同的設定
- 可以靠環境變數來判斷要使用哪種環境
- 也可以通過 sys 或 os modules 來判別
# Item 87: 定義 root exception 來隔絕所有從 API 呼叫的
- 抓住 root exceptions 可以幫助你找到從 API 報出來的 bug
- 抓住 python exceptions 幫助找到 API implementations 的 bug
- 中介的 root exceptions 可讓你添加更多更多特定類型的 exceptions 而又不會破壞 API 的使用
# Item 88: 知道如何處理 circular dependencies
- Circular dependencies 發生在兩個 modules 互相需要 import 對方時, 會造成程式剛啟動時 crash
- 最好的解決方式為重構兩個 modules, 讓要import 的內容到一個獨立的 module
- Dynamic import 是最為輕鬆且快速的解決方法
# Item 89: 要重構及做遷移使用時, 考慮 warning module
- 當你的 API 過時了, warning module 用於通知使用者, 免於日後讓程式產生錯誤
- 使用 -W error 指令 raise warning as errors, 可以有效測試找出潛在過時的 dependencies
- 在 production 環境, 可以複製 warning 訊息到 log module 來確保警告訊息有被收集到
- 寫測試來驗證程式是否會在對的時間點對有修改的 dependencies 產生警示訊息是很有用的
# Item 90: 考慮經過 typing 做 static analysis 來消除 bugs
- Python 有特殊的語法及內建的 typing, 來做 type information
- Static type checkers 可以做 type information 來幫助你避免於執行時發生錯誤
- 有許多的方法可以來可以來做 types, 使用它們於 API 中, 確保不會在 production 出現問題
有問題或是有錯誤的地方, 歡迎留言與我討論, 謝謝您。
[embed]Previous article: Effective python note chapter 9 第九章: Testing and Debuggingmedium.com
메타데이터
- post_id
- 6ca7115974cd
- slug
- effective-python-note-chapter-10-6ca7115974cd
- url
- https://medium.com/@nickest14/effective-python-note-chapter-10-6ca7115974cd
- canonical_url
- https://medium.com/@nickest14/effective-python-note-chapter-10-6ca7115974cd
- author_url
- https://medium.com/@nickest14
- status
- ok
- fetched_at
- 2026-07-15 22:34:01