How to Define a Mock Primary Metric in Python

Define a mock primary metric object with a name, value, and unit, and serialize it to a dictionary for experimentation and testing.

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

Python code

26 lines
Python 3.9+
class Metric:
    def __init__(self, name, value, unit=None):
        self.name = name
        self.value = value
        self.unit = unit

    def to_dict(self):
        result = {"name": self.name, "value": self.value}
        if self.unit:
            result["unit"] = self.unit
        return result

    def __repr__(self):
        return f"Metric(name={self.name!r}, value={self.value!r}, unit={self.unit!r})"


def define_primary_metric(name="response_time", value=0, unit="ms"):
    """Return a mock primary metric object."""
    return Metric(name=name, value=value, unit=unit)


if __name__ == "__main__":
    primary = define_primary_metric()
    print(primary.to_dict())
    primary_updated = define_primary_metric(value=120.5, unit="ms")
    print(primary_updated.to_dict())

Output

stdout
{'name': 'response_time', 'value': 0, 'unit': 'ms'}
{'name': 'response_time', 'value': 120.5, 'unit': 'ms'}

How it works

The Metric class stores a metric's name, value, and optional unit. The to_dict method converts the object into a plain dictionary, omitting the unit key if it is falsy, which keeps the output clean for logging or serialization. The define_primary_metric function returns a default mock metric or a customized one when arguments are passed. Using a mock metric lets you test experiment pipelines without waiting for real data.

Common mistakes

  • Forgetting to omit the unit key when unit is None, causing unexpected keys in the dictionary.
  • Mutating the default metric's attributes in place, which can affect other test cases.
  • Not using `__repr__` for debugging, making it harder to inspect metric objects in logs.

Variations

  1. Use a dataclass with `@dataclass` and a `to_dict` method for cleaner code.
  2. Store metrics in a dictionary directly and skip the class entirely.

Real-world use cases

  • Simulating experiment metrics in A/B test pipelines before real data is available.
  • Creating mock response time metrics for load testing and performance validation.
  • Providing default metric definitions in configuration systems for feature flag rollouts.

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.