How to Create a Mock That Returns Inverse Counter Values in Python

Builds a Mock whose side_effect returns the inverse (1/count) of each Counter value, defaulting to 0.0 for unseen keys.

Easy Python 3.9+ Aug 9, 2026 A/B testing & experimentation 13 views 0 copies

Python code

21 lines
Python 3.9+
from collections import Counter
from unittest.mock import Mock

def inverse_mock(counter: Counter) -> Mock:
    """
    Return a Mock that mimics the inverse of a Counter:
    each key returns a value representing the inverse of its count.
    The Mock's side_effect maps keys to their inverse counts.
    """
    mock = Mock()
    inverse_map = {key: 1 / count for key, count in counter.items()}
    mock.side_effect = lambda key: inverse_map.get(key, 0.0)
    return mock

if __name__ == "__main__":
    counter = Counter({"apple": 5, "banana": 2, "orange": 4})
    mock = inverse_mock(counter)
    print(mock("apple"))   # 0.2
    print(mock("banana"))  # 0.5
    print(mock("orange"))  # 0.25
    print(mock("grape"))   # 0.0 (unseen key)

Output

stdout
0.2
0.5
0.25
0.0

How it works

The Mock object's side_effect is set to a lambda that looks up keys in an inverse map, computing 1 / count for each item in the Counter. Dictionary .get(key, 0.0) ensures unseen keys return 0.0 instead of raising KeyError. This pattern allows test code to simulate computations based on event frequencies without implementing the full inverse logic. The lambda is called whenever the mock is invoked, mimicking the behavior of a callable that maps inputs to inverse-count outputs.

Common mistakes

  • Forgetting that 'side_effect' replaces the return value when set as a callable
  • Using 'return_value' instead of 'side_effect' for dynamic per-argument responses
  • Not handling unseen keys, causing KeyError instead of a sensible default
  • Dividing by zero if a Counter contains a zero count

Variations

  1. Use a defaultdict(float) with computed inverses for safer lookups
  2. Return 1 for zero counts by adding an if/else inside the lambda

Real-world use cases

  • In A/B tests, mock inverse conversion rates to simulate user behavior variants during rollout.
  • When unit testing statistical models, mock inverse frequency weights to verify sampling logic.
  • In experimentation pipelines, mock inverse CPS metrics to validate alert thresholds without heavy computation.

Sponsored

Run this sample

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

Open editor

More from A/B testing & experimentation

Related tutorials and quizzes for this topic.