a clean way to define dictionary

Alexander Schmolck a.schmolck at gmx.net
Wed Jun 18 16:06:55 EDT 2003


Just <just at xs4all.nl> writes:

> In article <yfs65n39z72.fsf at black132.ex.ac.uk>,
>  Alexander Schmolck <a.schmolck at gmx.net> wrote:
> 
> > > In 2.3, you can express this as dict(foo=1, bar='sean') without a
> > > need to define a function for the purpose.
> > 
> > Yuck! This seems like a really bad idea to me. This effectively makes it
> > impossible to specify any options (such as initial size, default value etc.)
> > at dict creation for dict subclasses or lookalikes or indeed future versions
> > of dict itself! Not a good tradeoff for minor syntactic sugar, IMO! If this
> > sugar is really needed, couldn't dict grow an appropriate classmethod instead
> > (e.g dict.with(foo=1, bar='sean))?
> 
> Using keyword args to build a dict is useful *now*; if dicts were to 
> ever grow extra constructions options, this could be still done with 
> class methods...

Not necessarily, since classmethods are strictly less powerful than
constructer calls (how do you propose to get 'initial size' to work with a
classmethod?). It also seems backwards to me: to my mind a constructor should
provide the full interface to instance creation and classmethods that also
return new instances should be useful specializations or sugar based on the
constructor, not the other way around.

Maybe I'm a bit blinkered, but right now I can't see how

    dict(foo=1, bar='sean')

is so much better/more convinient than

    {'foo':1, bar:'sean'}

that it justifies forcing people to learn a new redundant and less general
dictionary creation syntax that at least hinders customizing dictionary
instantiation like in

  counts = dict(default=0)
  for item in seq:
      counts[item] += 1

To get the first behavior you have to write a 1-line function, for the second
you have to subclass (and presumably incur a noticeable performance penalty).
Also the first precludes adding further constructor options, while the second
doesn't.


'as




More information about the Python-list mailing list