Contextmanager (Python)

from contextlib import contextmanager
 
@contextmanager
def managed_file(filename):
    # Setup phase
    file = open(filename, 'w')
    try:
        yield file  # Execution pauses here while the 'with' block runs
    finally:
        # Cleanup phase (guaranteed to execute)
        file.close()