from collections import Counter class Metrics: def __init__(self): self.counts = Counter() def observe(self, network, outcome): if network not in ('main', 'test') or outcome not in ('accepted', 'rejected', 'unknown'): raise ValueError('invalid label') self.counts[network, outcome] += 1 def unknown_ratio(self, network): total = sum(v for (n, _), v in self.counts.items() if n == network) return self.counts[network, 'unknown'] / total if total else None m = Metrics() assert m.unknown_ratio('test') is None m.observe('test', 'unknown') m.observe('test', 'accepted') assert m.unknown_ratio('test') == 0.5