从上下文管理器的数据模型文档中:
请注意,
__exit__()
方法不应重新引发传入的异常;这是调用者的责任。
我有一个临时文件,我想释放它的文件描述符,close
但不向磁盘写入任何内容。我直观的解决方案是传递异常,但在文档中不鼓励这样做——当然是有充分理由的。
class Processor(object):
...
def write(self, *args, **kwargs):
if something_bad_happens:
raise RuntimeError('This format expects %s columns: %s, got %s.' % (
(len(self.cols), self.cols, len(args))))
self.writer.writerow(args)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
# the RuntimeError from write will be set as type, value and so on ..
# I'd like to close the stream here (release the file descriptor),
# but I do not leave a trace of the associated file -
# (one can always 'manually' delete with `os.remove` but maybe there's a
# better way ..?)
self.output_pipe.close()
此外,在这种特殊情况下,我不希望在调用者中进行错误处理,原因有两个:
- 保持调用者中的代码最少(见下文)
- 调用者对异常感到满意(快速失败是我们想要的)
上下文管理器的使用如下:
class Worker(object):
...
def run(self):
# output setup so it will emit a three column CSV
with self.output().open('w') as output:
output.write('John', 'CA', 92101)
output.write('Jane', 'NY', 10304)
# should yield an error, since only three 'columns' are allowed
output.write('Hello', 'world')
更新:我的问题有点表述不当,因为我的问题实际上归结为:在嵌套的上下文管理器中,如何将异常传递给最外层的 CM?