での例外の再調達:__exit__()
メソッドは、渡された例外を再呼出しべきではないとは、コンテキストマネージャ上<a href="http://docs.python.org/2/reference/datamodel.html#object.__exit__" rel="nofollow">datamodel docs</a>からコンテキストハンドラ
注意を。これは発信者の責任です。
私は、そのファイル記述子私はclose
ではなく、ディスクには何も記述せずに解放したいのですが、一時ファイルを、持っています。私の直感的な解決策は、例外を渡すことでしたが、それはdiscouraged in the docsです - と確かに良い理由があります。また
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()
私は2つの理由から、呼び出し側では、この特定の場合のエラー処理にはしたくない。(下記参照)、最小、呼び出し元のコードを維持するために
- 呼び出し側が満足しています例外を除いて
コンテキストマネージャは、このようなものを使用されている(速いが、私たちはここに何をしたいです失敗):
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')
アップデート:私の問題は、本当にこれに煮詰めとして私のquesionは少し病気で処方されました:ネストされたコンテキストマネージャでは、どのように私は、最も外側のCMに上の例外を渡すことができますか?
あなたが本当に__exit__' 'で二回出力を閉じるようにもしかして:あなたは
__enter__
にを変更する必要がありますか? – user2357112@ user2357112、ここには含まれていないコードがたくさんあるので、コードは簡潔に見え、文脈に合わせるのが難しいかもしれません。申し訳ありません。私の質問が更新されました。私は 'output_pipe'を2回閉じません。 – miku