from contextlib import contextmanager @contextmanager def custom_context(name): print(f"進入上下文: {name}") try: yield name # 提供資源 finally: print(f"退出上下文: {name}") # 使用 with 語法 with custom_context("示範") as ctx: print(f"內部執行: {ctx}")