Can you use `with` on multiple items at once? How are they handled?

Python interview question for Advanced practice.

Answer

Yes, with A() as a, B() as b: works. Handling: It acts like nested blocks: with A() as a: with B() as b:. Error Handling: If A().enter succeeds but B().enter raises an exception, A().exit is called immediately to cleanup A. Python ensures that any successfully entered context is correctly exited, even if a subsequent context in the chain fails.

Explanation

If one fails to enter, the previous ones are exited automatically.

Related Questions