Yeah, with also provides a nice finalization call, but there are a few differences:
- with requires the subject to implement a particular interface.
- multiple with calls either nest, or they execute in the order they’re written, as soon as you exit the block. Multiple withs nest uncomfortably deep.
Go’s defer, and this she’ll one, turn statements into a stack where the past defer executes first on exit.
contextlib from the standard library, specifically contextlib.ExitStack, provide the rest of the patterns you might want to use with 'with'. Including removing the need for nested 'with' block, and non-lexical finalization orders.
https://docs.python.org/3/reference/compound_stmts.html#the-...