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

**URL:** <https://discuss.python.org/t/function-level-indent-less-with-to-do-cleanup-when-function-exits/108958>\
**Category:** Ideas\
**Created:** [September 8, 2026, 7:44pm UTC](https://discuss.python.org/t/function-level-indent-less-with-to-do-cleanup-when-function-exits/108958 "2026-09-08T19:44:10Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![bswck](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/bswck/32/34363_2.png) [@bswck](https://discuss.python.org/u/bswck)\
**Post date:** [September 8, 2026, 10:30pm UTC](https://discuss.python.org/t/function-level-indent-less-with-to-do-cleanup-when-function-exits/108958/8 "2026-09-08T22:30:28Z")

</div>

> [@techvslife](#):
>
> `def process(): `  
> ` with managed_resource() as db, open("example.txt", "r") as file:`  
> ` # All lines have to be indented if they might rely on db and file`  
> ` return "Done"`

```py
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.

---

_[View the full topic](https://discuss.python.org/t/function-level-indent-less-with-to-do-cleanup-when-function-exits/108958)._
