Function-level (indent-less) "with" to do cleanup when function exits

from contextlib import ExitStack

def process():
    resources = ExitStack()
    db = resources.enter_context(managed_resource())
    file = resources.enter_context(open("example.txt", "r"))

    # Do the things with db and file...

    resources.close()
    return "Done"

I think this is quite clean and is supported by Python out of the box.
Works everywhere and adds zero indentation to your code.

5 Likes