← All Exercises

Context Manager That Guarantees Cleanup

intermediatepython~20min

Background

Context managers encode acquire/use/release and commit/rollback protocols so cleanup runs even when the body raises.

Problem

Implement a Transaction context manager over a dictionary ledger. set(key, value) buffers writes; __exit__ commits buffered writes when the block succeeds, discards them when it raises, marks the transaction closed in both cases, and does not suppress the exception.

Input

A ledger dictionary and a scenario flag indicating whether the block raises ValueError.

Output

The committed ledger contents and the transaction closed flag.

Sample tests

Sample 1

Input: ledger = {}, fail = False
Expected: ({'a': 1, 'b': 2}, True)

Sample 2

Input: ledger = {}, fail = True
Expected: ({}, True)

Your solution

Learning objective

Use the context manager protocol for atomic commit or rollback and predictable cleanup.