from contextlib import contextmanager
@contextmanager
def access_resource(name):
print('Acquiring resource:', name)
res = []
try:
yield res
finally:
print('Releasing resource:', name, res)
with access_resource('To-Do List') as xs:
print('Add To-Do Items')
xs.append('Item 1')
xs.append('Item 2')
with access_resource('Finished List') as xs:
raise KeyError('Impossible')
Item 11: Context Manager
Posted by Logan Chien