How to Mock a Try Confirm Cancel Pattern in Python

Define a simple class with confirm and cancel methods, execute a try confirm with error handling, and print the final state.

Easy Python 3.9+ Aug 9, 2026 Reliability & rate limiting 13 views 0 copies

Python code

25 lines
Python 3.9+
class TCC:
    def __init__(self):
        self.confirmed = False
        self.cancelled = False

    def confirm(self):
        self.confirmed = True
        return "confirmed"

    def cancel(self):
        self.cancelled = True
        return "cancelled"

    def try_confirm(self):
        try:
            result = self.confirm()
            print(f"Try confirm → {result}")
        except Exception as e:
            print(f"Try confirm failed: {e}")

if __name__ == "__main__":
    tcc = TCC()
    tcc.try_confirm()
    print(f"Cancel result: {tcc.cancel()}")
    print(f"Final state: confirmed={tcc.confirmed}, cancelled={tcc.cancelled}")

Output

stdout
Try confirm → confirmed
Cancel result: cancelled
Final state: confirmed=True, cancelled=True

How it works

The try_confirm method wraps the confirm call in a try-except block, printing a success message when no error occurs. The confirm and cancel methods simply set boolean flags and return string results. Running the main block demonstrates the sequence: a successful confirm, a cancel, and the final state. This pattern is useful for testing mockable operations where you want to ensure fallback behavior on exceptions.

Common mistakes

  • Forgetting to reset flags before reusing the object
  • Not catching specific exceptions in the try block
  • Assuming the return value is used when it's only printed

Variations

  1. Use a mock library like unittest.mock to replace confirm or cancel in tests
  2. Add retry logic with exponential backoff inside try_confirm

Real-world use cases

  • Testing service interactions where confirmation or cancellation must be idempotent.
  • Building retry mechanisms for unreliable remote calls in distributed systems.
  • Implementing user-facing actions that need explicit success or failure logging.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Reliability & rate limiting

Related tutorials and quizzes for this topic.