Context manager for a scoped transaction log

Python data engineering interview problem. Difficulty: advanced. Pattern: OOP. About 20 minutes. Part of the Pro drill bank.

A job writes a transaction log that must close even if the body fails. A context manager is the Python way to guarantee setup/teardown.

A transaction runs a list of steps. If every step works the transaction is committed. If a step fails, it is rolled back and the remaining steps do not run. ops is a list of step results, where 'err' marks a failed step. Run the steps in order and count how many ran (including the failing one). If any step is 'err', stop and return {'status': 'rolled_back', 'ran': count}. If none fail, return {'status': 'committed', 'ran': count}. Write run_transaction(ops). For ['ok', 'ok'] the result is {'status': 'committed', 'ran': 2}. For ['ok', 'err', 'ok'] the second step fails, so the result is {'status': 'rolled_back', 'ran': 2} and the third step never runs. The starter file already has the function name and its print lines. Keep them and fill in the body.

Requirements

  • Run the steps in order.
  • Count each step that runs, including the failing one.
  • Stop at the first 'err'.
  • Return 'committed' or 'rolled_back' with the count.

Constraints

  • ops is a list of text values such as 'ok' and 'err'.
  • The result is a dictionary with status and ran.

Examples

Input: run_transaction(['ok', 'ok']) Output: {'status': 'committed', 'ran': 2} This input follows the stated rules and produces this output.

Topics: lakebench, python, OOP.

More Python interview questions · All interview problems · Learn data engineering

advanced

Context manager for a scoped transaction log

Interview-style drill: Write a context manager that records whether a block of operations completed or raised an error.

Implement a context manager that records a scoped transaction log as the tests specify.