This commit is contained in:
Joachim Jablon
2016-03-17 00:25:34 +01:00
parent 2839c219fe
commit a37543f242
+7 -3
View File
@@ -658,8 +658,10 @@ And now the generator approach using Python's own
@contextmanager @contextmanager
def custom_open(filename): def custom_open(filename):
f = open(filename) f = open(filename)
yield f try:
f.close() yield f
finally:
f.close()
with custom_open('file') as f: with custom_open('file') as f:
contents = f.read() contents = f.read()
@@ -667,7 +669,9 @@ And now the generator approach using Python's own
This works in exactly the same way as the class example above, albeit it's 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`` more terse. The ``custom_open`` function executes until it reaches the ``yield``
statement. It then gives control back to the ``with`` statement, which assigns 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 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 to decide when to use which. The class approach might be better if there's