Interlacing ContextManager

Good point, the context managers should be nested to ensure the second resource is cleaned up promptly rather than when the exit stack is garbage collected:

with contextlib.ExitStack() as outer_with:
  with first_resource:
    do_something()
    outer_with.enter_context(
        second_resource
    )
    do_combined_thing()
   do_something_else()

Edit: for the other part of your question, context managers added to the stack receive exception details and can suppress exceptions as normal (otherwise they wouldn’t work as expected), but plain callbacks do not.

1 Like