相关疑难解决方法(0)

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

我知道这已被广泛讨论,但我仍然找不到答案来证实这一点:with语句与在try - (除了)-finally块中调用相同代码相同,其中无论在__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..."
Run Code Online (Sandbox Code Playgroud)

同样如下:

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")
Run Code Online (Sandbox Code Playgroud)

谢谢!

python with-statement contextmanager

19
推荐指数
1
解决办法
3509
查看次数

标签 统计

contextmanager ×1

python ×1

with-statement ×1