Pre-PEP: Dictionary accumulator methods

Kay Schluehr kay.schluehr at gmx.net
Sat Mar 19 23:07:40 EST 2005


George Sakkis wrote:
> > -1 form me.
> >
> > I'm not very glad with both of them ( not a naming issue ) because
i
> > think that the dict type should offer only methods that apply to
each
> > dict whatever it contains. count() specializes to dict values that
are
> > addable and appendlist to those that are extendable. Why not
> > subtractable, dividable or right-shiftable? Because of majority
> > approval? I'm mot a speed fetishist and destroying the clarity of a
> > very fundamental data structure for speedup rather arbitrary
> > accumulations seems to be a bad idea. I would move this stuff in a
> > subclass.
> >
> > Regards Kay

> +1 on this. The new suggested operations are meaningful for a subset
of all
> valid dicts, so they
> should not be part of the base dict API. If any version of this is
approved, > it will clearly be an
> application of the "practicality beats purity" zen rule, and the
> justification for applying it in
> this case instead of subclassing should better be pretty strong; so
far I'm
> not convinced though.
>
> George

It is bad OO design, George. I want to be a bit more become more
specific on this and provide an example:

Let be <intdict> a custom subclass of dict that stores only ints as
keys as well as values:

class intdict(dict):
    def __setitem__(self, key, value):
        assert isinstance(key, int) and isinstance(value, int)
        dict.__setitem__(self,key,value)

or in Python3000 typeguard fashion:

class intdict(dict):
    def __setitem__(self, key:int, value:int):
        dict.__setitem__(self,key,value)

But <intdict> still overloads appendlist() i.e. a method that does not
work for any intdict is still part of it's public interface! This is
really bad design and should not be justified by a "practicality beats
purity" wisdom which should be cited with much care but not
carelesness.

Maybe also the subclassing idea I introduced falls for short for the
same reasons. Adding an accumulator to a dict should be implemented as
a *decorator* pattern in the GoF meaning of the word i.e. adding an
interface to some object at runtime that provides special facilities.

Usage:

>>> d = intdict(extend=MyAccumulator)
>>> hasattr(d,"tally")
True
>>> hasattr(d,"appendlist")
False

This could be generalized to other fundamental data structures as well.

Regards Kay




More information about the Python-list mailing list