隨著開源協作盛行,良好的套件結構至關重要。本文歸納五項核心準則,助你建立可維護、可擴展、無循環依賴的 Python 套件。
__init__.py 僅服務「導入」錯誤做法: 將工具函數、異常類別、常數塞進 __init__.py。
正確做法: 僅作為子模組匯入口,按依賴順序導入:
# mypkg/__init__.py
# 順序很重要:被依賴者優先
from .exceptions import MyError, OtherError
from . import constants
from .const import const, set_const
from . import path
from .lists import hosts, queues
# ...
好處:
from mypkg import foo 即可使用,無需知曉內部結構__init__.py 限制導入順序、定義 __all____all__ = [
'MyError', 'OtherError',
'constants', 'const', 'set_const',
'path', 'hosts', 'queues',
# ...
]
__all__ 明確宣告公開 API,配合 from mypkg import *# exceptions.py
class MyPkgError(Exception):
"""根異常,捕獲所有套件錯誤用"""
pass
class ConfigError(MyPkgError): pass
class EncodeError(MyPkgError): pass
class EnqueueError(MyPkgError): pass
# ... 20+ 細粒度異常
優勢:
except MyPkgError 捕獲所有錯誤except EnqueueError: / except ScanError:# 子模組內
from .exceptions import MyError # 正確
from mypkg.exceptions import MyError # 錯誤:依賴安裝路徑、套件名
相對導入確保:
(原文第五點被截斷,補充常見最佳實務:)
__version__ 放在 __init__.py 或 _version.pytests/ 置於套件外層,用 pytest 發現setup.cfg / pyproject.toml 靜態宣告元資料遵循這五大準則,你的 Python 套件將具備專業級結構:清晰的邊界、可控的依賴、友善的 API、易於測試與發布。