Advertisement
rfmonk

contextlib_contextmanager.py

Jan 16th, 2014
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.55 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import contextlib
  5.  
  6.  
  7. @contextlib.contextmanager
  8. def make_context():
  9.     print '  entering'
  10.     try:
  11.         yield {}
  12.     except RuntimeError, err:
  13.         print ' ERROR:', err
  14.     finally:
  15.         print ' exiting'
  16.  
  17. print 'Normal:'
  18. with make_context() as value:
  19.     print '  inside with statement:', value
  20.  
  21. print '\nHandled error:'
  22. with make_context() as value:
  23.     raise RuntimeError('showing example of handling an error')
  24.  
  25. print '\nUnhandled error:'
  26. with make_context() as value:
  27.     raise ValueError('this exception is not handled')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement