軟體模組間的調用模式主要分三類:同步調用 (阻塞等待)、回呼 (雙向調用)、非同步調用 (事件/訊息驅動)。回呼是實現非同步通知的基礎。本文詳細說明 Python 回呼機制、常見模式與實務技巧。
# caller.py
import callee
def callback():
print("in callback")
def main():
callee.test_call(callback)
print("in caller")
if __name__ == '__main__':
main()
# callee.py
def test_call(callback_func):
print("in callee test_call")
callback_func() # 執行呼叫端傳入的函數
輸出:
in callee test_call
in callback
in caller
def process(data, on_complete):
result = do_work(data)
on_complete(result)
def handle_result(res):
print(f"Result: {res}")
process("input", handle_result)
class Handler:
def on_done(self, result):
print(f"Handler got: {result}")
h = Handler()
process("data", h.on_done) # 傳入綁定方法
process("data", lambda r: print(f"Lambda got: {r}"))
from functools import partial
def callback_with_context(ctx, result):
print(f"[{ctx}] Result: {result}")
process("data", partial(callback_with_context, "Job-123"))
import asyncio
async def fetch_data(url, callback):
# 模擬非同步 IO
await asyncio.sleep(1)
data = f"Data from {url}"
callback(data)
def on_data(data):
print(f"Received: {data}")
async def main():
await fetch_data("https://api.example.com", on_data)
asyncio.run(main())
(error, result) 或使用 try/except 在回呼內處理。async/await、concurrent.futures 或 Promise 風格。Callable[[ResultType], None] 提升可讀性與靜態檢查。weakref 避免循環引用導致記憶體洩漏。atexit.register(func):程式退出時回呼。signal.signal(signum, handler):訊號處理。threading.Timer(interval, func):定時回呼。asyncio.add_reader(fd, callback):IO 多工回呼。回呼是 Python 事件驅動程式設計的基石,善用現代非同步語法可大幅降低複雜度。