File tree Expand file tree Collapse file tree 1 file changed +7
-3
lines changed Expand file tree Collapse file tree 1 file changed +7
-3
lines changed Original file line number Diff line number Diff line change @@ -658,16 +658,20 @@ And now the generator approach using Python's own
658
658
@contextmanager
659
659
def custom_open (filename ):
660
660
f = open (filename)
661
- yield f
662
- f.close()
661
+ try :
662
+ yield f
663
+ finally :
664
+ f.close()
663
665
664
666
with custom_open(' file' ) as f:
665
667
contents = f.read()
666
668
667
669
This works in exactly the same way as the class example above, albeit it's
668
670
more terse. The ``custom_open `` function executes until it reaches the ``yield ``
669
671
statement. It then gives control back to the ``with `` statement, which assigns
670
- whatever was ``yield ``'ed to `f ` in the ``as f `` portion.
672
+ whatever was ``yield ``'ed to `f ` in the ``as f `` portion. The ``finally `` clause
673
+ ensures that ``close() `` is called whether or not there was an exception inside
674
+ the ``with ``.
671
675
672
676
Since the two approaches appear the same, we should follow the Zen of Python
673
677
to decide when to use which. The class approach might be better if there's
You can’t perform that action at this time.
0 commit comments