Python *与*语句完全等同于尝试 - (除外) - finally块?

时间:2014-09-29 09:18:48

标签: python with-statement contextmanager

我知道这已被广泛讨论,但我仍然无法找到答案来确认这一点:语句是否相同于在try中调用相同的代码 - (除外)-finally block ,在上下文管理器的__exit__函数中定义的任何内容放在finally块中?

例如 - 这两个代码片段完全相同吗?

import sys
from contextlib import contextmanager

@contextmanager
def open_input(fpath):
    fd = open(fpath) if fpath else sys.stdin
    try:
        yield fd
    finally:
        fd.close()

with open_input("/path/to/file"):
    print "starting to read from file..."

与:

相同
def open_input(fpath):
    try:
        fd = open(fpath) if fpath else sys.stdin
        print "starting to read from file..."
    finally:
        fd.close()

open_input("/path/to/file")

谢谢!

1 个答案:

答案 0 :(得分:26)

我会撇开范围提及,因为它确实不太相关。

根据PEP 343

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)

如您所见,type(mgr).__enter__按照您的预期调用,但不在try 内。

退出时调用

type(mgr).__exit__。唯一的区别是当出现异常时,会采用if not exit(mgr, *sys.exc_info())路径。这使with能够反省和沉默错误,这与finally子句不同。


contextmanager并不会使很多复杂化。它只是:

def contextmanager(func):
    @wraps(func)
    def helper(*args, **kwds):
        return _GeneratorContextManager(func, *args, **kwds)
    return helper

然后看看有问题的课程:

class _GeneratorContextManager(ContextDecorator):
    def __init__(self, func, *args, **kwds):
        self.gen = func(*args, **kwds)

    def __enter__(self):
        try:
            return next(self.gen)
        except StopIteration:
            raise RuntimeError("generator didn't yield") from None

    def __exit__(self, type, value, traceback):
        if type is None:
            try:
                next(self.gen)
            except StopIteration:
                return
            else:
                raise RuntimeError("generator didn't stop")
        else:
            if value is None:
                value = type()
            try:
                self.gen.throw(type, value, traceback)
                raise RuntimeError("generator didn't stop after throw()")
            except StopIteration as exc:
                return exc is not value
            except:
                if sys.exc_info()[1] is not value:
                    raise

已经省略了不重要的代码。

首先要注意的是,如果有多个yield,则此代码会出错。

这不会明显影响控制流程。

考虑__enter__

try:
    return next(self.gen)
except StopIteration:
    raise RuntimeError("generator didn't yield") from None

如果上下文管理器编写得很好,那么这绝不会违背预期。

一个区别是,如果生成器抛出StopIteration,将产生不同的错误(RuntimeError)。这意味着该行为与正常行为不完全相同{ {1}}如果您正在运行完全任意的代码。

考虑一个无错误的with

__exit__

唯一的区别是和以前一样;如果您的代码抛出if type is None: try: next(self.gen) except StopIteration: return else: raise RuntimeError("generator didn't stop") ,它将影响生成器,因此StopIteration装饰器会误解它。

这意味着:

contextmanager

哪个不太重要,但可以。

最后:

from contextlib import contextmanager

@contextmanager
def with_cleanup(func):
    try:
        yield
    finally:
        func()

def good_cleanup():
    print("cleaning")

with with_cleanup(good_cleanup):
    print("doing")
    1/0
#>>> doing
#>>> cleaning
#>>> Traceback (most recent call last):
#>>>   File "", line 15, in <module>
#>>> ZeroDivisionError: division by zero

def bad_cleanup():
    print("cleaning")
    raise StopIteration

with with_cleanup(bad_cleanup):
    print("doing")
    1/0
#>>> doing
#>>> cleaning

这提出了关于else: if value is None: value = type() try: self.gen.throw(type, value, traceback) raise RuntimeError("generator didn't stop after throw()") except StopIteration as exc: return exc is not value except: if sys.exc_info()[1] is not value: raise 的相同问题,但有趣的是注意到最后一部分。

StopIteration

这意味着如果未处理异常,则回溯将保持不变。如果它已被处理但存在 new 回溯,则会引发该回溯。

这完全符合规范。


TL; DR

  • if sys.exc_info()[1] is not value: raise 实际上比with更强大,因为try...finally可以内省并消除错误。

  • 请注意with,否则您可以使用StopIteration创建上下文管理器。