Skip to content

Commit a37543f

Browse files
committed
1 parent 2839c21 commit a37543f

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

docs/writing/structure.rst

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff 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
668670
more terse. The ``custom_open`` function executes until it reaches the ``yield``
669671
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``.
671675

672676
Since the two approaches appear the same, we should follow the Zen of Python
673677
to decide when to use which. The class approach might be better if there's

0 commit comments

Comments
 (0)