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


Groups > comp.lang.python > #100473 > unrolled thread

Re: subclassing collections.Counter

Started byPavlos Parissis <pavlos.parissis@gmail.com>
First post2015-12-15 17:59 +0100
Last post2015-12-15 17:59 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: subclassing collections.Counter Pavlos Parissis <pavlos.parissis@gmail.com> - 2015-12-15 17:59 +0100

#100473 — Re: subclassing collections.Counter

FromPavlos Parissis <pavlos.parissis@gmail.com>
Date2015-12-15 17:59 +0100
SubjectRe: subclassing collections.Counter
Message-ID<mailman.34.1450198801.22044.python-list@python.org>

[Multipart message — attachments visible in raw view] — view raw

On 15/12/2015 05:18 μμ, Pavlos Parissis wrote:
> On 15/12/2015 05:08 μμ, Peter Otten wrote:
>> 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__().
>>
>>
>>
> 
> I applied your suggestion and worked!
>    def __getitem__(self, key):
>         if (self.avg_metrics is not None and key in self.avg_metrics):
>             return super().__getitem__(key) / self.__counter
>         else:
>             return super().__getitem__(key)
> 
> Thank you very much,
> Pavlos
> 

Calling items() over the object doesn't call __getitem__ and I can't
find in the doc which method I need to change, any ideas?

Cheers,
Pavlos

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web