subclassing collections.Counter

Ian Kelly ian.g.kelly at gmail.com
Tue Dec 15 12:55:05 EST 2015


On Tue, Dec 15, 2015 at 10:43 AM, Pavlos Parissis
<pavlos.parissis at gmail.com> wrote:
>> If you want your metrics container to act like a dict, then my
>> suggestion would be to just use a dict, with pseudo-collections for
>> the values as above.
>>
>
> If I understood you correctly, you are saying store all metrics in a
> dict and have a counter key as well to store the times metrics are
> pushed in, and then have a function to do the math. Am I right?

That would work, although I was actually thinking of something like this:

class SummedMetric:
    def __init__(self):
        self.total = 0
        self.count = 0

    @property
    def average(self):
        return self.total / self.count

    def add(self, value):
        self.total += value
        self.count += 1

metrics = {}
for metric_name in all_metrics:
    metrics[metric_name] = SummedMetric()

For averaged metrics, look at metrics['f'].average, otherwise look at
metrics['f'].total.



More information about the Python-list mailing list