datamodel docs से संदर्भ प्रबंधकों पर फिर से ऊपर उठाने:एक अपवाद एक संदर्भ हैंडलर में
ध्यान दें कि
__exit__()
तरीकों से पारित कर दिया-इन अपवाद reraise नहीं होनी चाहिए; यह कॉलर की ज़िम्मेदारी है।
मैं एक अस्थायी फ़ाइल, जिसका फ़ाइल वर्णनकर्ता मैं 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()
इसके अलावा
मैं नहीं चाहता कि दो कारणों के लिए फोन करने वाले में इस विशेष मामले त्रुटि हैंडलिंग में हैं: कम से कम (नीचे देखें) फोन करने वाले में कोड रखने के लिए
- फोन करने वाले खुश है अपवादों को छोड़कर (असफल तेजी से हम यहाँ चाहते है)
संदर्भ प्रबंधक कुछ इस तरह किया जाता है:
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 थोड़ा बीमार तैयार के रूप में मेरी समस्या वास्तव में इस के लिए नीचे उबला हुआ था?
क्या आप वास्तव में '__exit__' में आउटपुट को दो बार बंद करना चाहते थे? – user2357112
@ user2357112, वहां और कोड है जिसे मैंने यहां शामिल नहीं किया है - इसलिए कोड टेर्स और शायद संदर्भित करना मुश्किल हो सकता है, इसके लिए खेद है। मेरा प्रश्न अपडेट किया गया, मैं 'output_pipe' को दो बार बंद नहीं करता हूं। – miku