Commit or Roll Back

Hard ⏱ 18 min 30% acceptance ★★★★★ 4.8
You get an object with .begin(), .commit(), .rollback() and a work callable. Write transact(db, work) implementing the classic pattern: begin, run work, commit and return its result — but on ANY exception roll back first, then re-raise. If the rollback itself raises, let the original work exception win (suppress the rollback error).

Examples

Example 1
Input
transact(db, lambda: save())
Output
result of save(), committed — or rolled back + original error re-raised
Explanation

Rollback failures never mask the real cause.

Constraints

  • Rollback errors must be suppressed.
  • The original exception propagates.

Topics

Exception Handlingtransaction pattern

Companies

Goldman SachsDeutsche BankHDFC Bank

Hints

Hint 1

Nest a try/except Exception: pass around the rollback call.

Hint 2

A bare raise after the inner try re-raises the original.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.