上下文管理器(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)