Python在with关键字的范围内扩展变量的生命周期

时间:2016-01-12 15:27:18

标签: python

假设我有代码打开一个带有with关键字的文件,我希望它在某些条件下关闭后保持打开状态。

所以假设最简单的功能:

def do_sth():
  with open('/tmp/foobar') as f:
    # do anything to stop f from closing

有没有办法规避python解释器调用f.__exit__()? 您可以假设,这应该适用于实施__enter____exit__的任何类。

到目前为止,我试图用另一个可关闭的对象替换f:

d = open('/tmp/bsdf')
with open('/tmp/asdf') as f:
    d,f = f,d
print "f {}, d {}".format(f.closed, d.closed)

一个潜在的用例是创建一个包装器,以便您可以执行以下操作:

with filehandle('foobar') as f:
  # do something

# don't close if filehandle returns sys.stdout.

1 个答案:

答案 0 :(得分:1)

在阅读pep-0343之后,我得出结论认为这不应该是语义的一部分。

我发现的唯一选择是编写自己的上下文管理器来执行条件发布。

from contextlib import contextmanager
import sys

@contextmanager
def custom_open(filename, mode='r'):
    if filename is 'stdout':
        yield sys.stdout
    else:
        try:
            f = open(filename, mode)
        except IOError, err:
            yield None
        else:
            try:
                yield f
            finally:
                f.close()


with custom_open('stdout') as f:
    f.write('hello world\n')
print "f {}".format(f.closed)

with custom_open('/tmp/foobar', 'w+') as f:
    f.write('hello world\n')
print "f {}".format(f.closed)