Advertisement
Guest User

Untitled

a guest
Jun 12th, 2013
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. with foo as bar:
  2.     baz()
  3.  
  4. # The fundamental, simple concept behind with is that
  5. # it's equivalent to this:
  6. bar = foo.__enter__()
  7. try:
  8.     baz()
  9. finally:
  10.     foo.__exit__(None, None, None)
  11.  
  12. # But there are less common cases where you don't just
  13. # want to clean up on exit, you want to do different cleanup
  14. # depending on whether you were exiting by exception or
  15. # normally. To make those cases work, with has an inner
  16. # try/except, to have somewhere to capture that information:
  17. bar = foo.__enter__()
  18. exc = (None, None, None)
  19. try:
  20.     try:
  21.         baz()
  22.     except:
  23.         exc = sys.exc_info()
  24.         raise
  25. finally:
  26.     foo.__exit__(*exc)
  27.  
  28. # Finally, there are even less common cases where you
  29. # want the context manager to be able to examine the exc
  30. # info and decide whether to swallow it or propagate it.
  31. # To make those cases work, you need a second __exit__
  32. # call in the inner block, at which point we're
  33. # effectively equivalent to what's specified in PEP 343:
  34. bar = foo.__enter__()
  35. no_exception = True
  36. try:
  37.     try:
  38.         baz()
  39.     except:
  40.         no_exception = False
  41.         if not foo.__exit__(*sys.exc_info()):
  42.             raise
  43. finally:
  44.     if no_exception:
  45.         foo.__exit__(None, None, None)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement