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.
Python code
26 linesclass 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
{'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
- Use a dataclass with `@dataclass` and a `to_dict` method for cleaner code.
- 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
More from A/B testing & experimentation
Keep learning
Related tutorials and quizzes for this topic.