Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #100467

Re: subclassing collections.Counter

From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: subclassing collections.Counter
Date 2015-12-15 17:08 +0100
Organization None
Message-ID <mailman.28.1450195721.22044.python-list@python.org> (permalink)
References <567036A5.6050205@gmail.com>

Show all headers | View raw


Pavlos Parissis wrote:

> I need to store values for metrics and return the average for some
> and the sum for the rest. Thus, I thought I could extend
> collections.Counter class by returning averages for some keys.
> 
> My class modifies the update() to increment a counter and the
> __getitem__ to perform the calculation. But, I get RuntimeError: maximum
> recursion depth exceeded as I access an attribute inside
> __getitem__.
> 
> Does anyone has an idea how I can achieve this?

> class CounterExt(Counter):

>     def __getitem__(self, key):
>         if (self.avg_metrics is not None and key in self.avg_metrics):
>             return self[key] / self._counter
>         else:
>             return self[key]

self[key] will call the CounterExt.__getitem__() method again. Use 
super().__getitem__(key) instead to invoke Counter.__getitem__().


Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: subclassing collections.Counter Peter Otten <__peter__@web.de> - 2015-12-15 17:08 +0100

csiph-web