Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- with foo as bar:
- baz()
- # The fundamental, simple concept behind with is that
- # it's equivalent to this:
- bar = foo.__enter__()
- try:
- baz()
- finally:
- foo.__exit__(None, None, None)
- # But there are less common cases where you don't just
- # want to clean up on exit, you want to do different cleanup
- # depending on whether you were exiting by exception or
- # normally. To make those cases work, with has an inner
- # try/except, to have somewhere to capture that information:
- bar = foo.__enter__()
- exc = (None, None, None)
- try:
- try:
- baz()
- except:
- exc = sys.exc_info()
- raise
- finally:
- foo.__exit__(*exc)
- # Finally, there are even less common cases where you
- # want the context manager to be able to examine the exc
- # info and decide whether to swallow it or propagate it.
- # To make those cases work, you need a second __exit__
- # call in the inner block, at which point we're
- # effectively equivalent to what's specified in PEP 343:
- bar = foo.__enter__()
- no_exception = True
- try:
- try:
- baz()
- except:
- no_exception = False
- if not foo.__exit__(*sys.exc_info()):
- raise
- finally:
- if no_exception:
- foo.__exit__(None, None, None)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement