[Python-Dev] collections module (original) (raw)
Raymond Hettinger python at rcn.com
Sat Jan 10 14:26:17 EST 2004
- Previous message: [Python-Dev] collections module
- Next message: [Python-Dev] collections module
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
[Martin]
I do believe that bag classes got into libraries only for academic reasons such as symmetry. In particular, they got into Smalltalk because of that reason, and everybody copies it because Smalltalk has it. This has to stop :-)
Some much for "everybody else has one" justification ;-)
Both applications could be implemented if dictionaries had the notion of a default value, which would be generated by a callable (whether with or without argument is debatable)
# count things d = {} d.defaultmaker = lambda k:0 for t in things: d[t] += 1 # sort things by category d = {} d.defaultmaker = lambda k:[] for t in things: d[category(t)].append(t)
These both read cleanly.
I really like this idea as a general purpose solution with broad applicability. It fully encapsulates the ideas behind bag construction and building dicts of lists.
Instead of a method, it may be better to use a keyword argument in the constructor:
d = dict(default = lambda k:[]) for t in things: d[category(t)].append(t)
If lambda is made parameterless, it allows type constructors to be used for the most common cases:
dict(default=list) # this is clear enough dict(default=int) # this may be too cute
Or, lambda could be avoided altogether by cloning a default value
dict(default=[]) # individual default values computed by copy([]) dict(default=0)
Having a key in the lambda is probably better, as it would also allow lazily-filled dictionaries.
Can you give an example?
Raymond Hettinger
- Previous message: [Python-Dev] collections module
- Next message: [Python-Dev] collections module
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]