Cleanup: Combine context managers and get it out of function

There is no need to have three separate context managers here. Also
putting it out of the function will allow further reuse and shortens
the function incresing code readability.