上下文管理器(with 語句)

上下文管理器在 PEP 343 中定義。與 try ... finally 結構相比,它們旨在用作更簡潔的資源管理機制。正式定義如下。

在此 PEP 中,上下文管理器提供了在進入和退出 with 語句主體時呼叫的 __enter__()__exit__() 方法。

然後繼續定義 with 語句如下。

with EXPR as VAR:
    BLOCK

上述宣告的譯文如下:

   mgr = (EXPR)
   exit = `type(mgr)`.__exit__  # Not calling it yet
   value = `type(mgr)`._`_enter__(mgr)`
   exc = True
   try:
       try:
           VAR = value  # Only if "as VAR" is present
           BLOCK
       except:
           # The exceptional case is handled here
           exc = False
           if not exit(mgr, *`sys.exc_info()`):
               raise
           # The exception is swallowed if `exit()` returns true
   finally:
       # The normal and non-local-goto cases are handled here
       if exc:
           exit(mgr, None, None, None)