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


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

Re: subclassing collections.Counter

Started byPavlos Parissis <pavlos.parissis@gmail.com>
First post2015-12-15 18:43 +0100
Last post2015-12-15 18:43 +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 18:43 +0100

#100476 — Re: subclassing collections.Counter

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

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

On 15/12/2015 06:22 μμ, Ian Kelly wrote:
> On Tue, Dec 15, 2015 at 9:20 AM, Pavlos Parissis
> <pavlos.parissis@gmail.com> wrote:
>> On 15/12/2015 05:11 μμ, Ian Kelly wrote:
>>> On Tue, Dec 15, 2015 at 8:49 AM, Pavlos Parissis
>>> <pavlos.parissis@gmail.com> wrote:
>>>> Hi,
>>>>
>>>> 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.
>>>
>>> Leave Counter out of it, as this is not what it's designed for. Write
>>> a custom Metrics class, with each attribute being a pseudo-collection
>>> that maintains a sum or average.
>>>
>>
>> But then I will have to override a lot of magic methods, right?
>> What is the real problem of extending Counter in the way I did?
> 
> Only the ones that you have use for. So far, you haven't indicated
> that you need any. All you said about your use case was "I need to
> store values for metrics."
> 

I needed the update() to do the addition rather the override.

> 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?

>> 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?
> 
> You can find the source at
> https://hg.python.org/cpython/file/3.5/Lib/collections/__init__.py.
> Counter subclasses dict but doesn't override items, so if you want to
> change the behavior of items then you'll probably have to override
> items.
> 

I thought that items() calls a magic method, but it is actually a method
itself. Thanks for highlight this.

Cheers,
Pavlos

[toc] | [standalone]


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


csiph-web