Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
ewjoachim committed Mar 16, 2016
1 parent 2839c21 commit a37543f
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions docs/writing/structure.rst
Original file line number Diff line number Diff line change
Expand Up @@ -658,16 +658,20 @@ And now the generator approach using Python's own
@contextmanager
def custom_open(filename):
f = open(filename)
yield f
f.close()
try:
yield f
finally:
f.close()
with custom_open('file') as f:
contents = f.read()
This works in exactly the same way as the class example above, albeit it's
more terse. The ``custom_open`` function executes until it reaches the ``yield``
statement. It then gives control back to the ``with`` statement, which assigns
whatever was ``yield``'ed to `f` in the ``as f`` portion.
whatever was ``yield``'ed to `f` in the ``as f`` portion. The ``finally`` clause
ensures that ``close()`` is called whether or not there was an exception inside
the ``with``.

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

0 comments on commit a37543f

Please sign in to comment.