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
658658 @contextmanager
659659 def custom_open (filename ):
660660 f = open (filename)
661- yield f
662- f.close()
661+ try :
662+ yield f
663+ finally :
664+ f.close()
663665
664666 with custom_open(' file' ) as f:
665667 contents = f.read()
666668
667669 This works in exactly the same way as the class example above, albeit it's
668670more terse. The ``custom_open `` function executes until it reaches the ``yield ``
669671statement. 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 ``.
671675
672676Since the two approaches appear the same, we should follow the Zen of Python
673677to 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