Pre-PEP: Dictionary accumulator methods - typing & initialising

Matteo Dell'Amico della at toglimi.linux.it
Sun Mar 20 14:23:50 EST 2005


Kay Schluehr wrote:

>>I think that's because you have to instantiate a different object for
>>each different key. Otherwise, you would instantiate just one list as
>>a default value for *all* default values.
> Or the default value will be copied, which is not very hard either or
> type(self._default)() will be called. This is all equivalent and it
> does not matter ( except for performance reasons ) which way to go as
> long only one is selected.

I don't like it very much... it seems too implicit to be pythonic. Also, 
it won't work with non-copyable objects, and type(42)() = 0, and getting 
0 when the default is 42 looks very strange. I prefer the explicit "give 
me a callable" approach.

> If the dict has a fixed semantics by applying defaultValue() and it
> returns defaults instead of exceptions whenever a key is missing i.e.
> behavioural invariance the client of the dict has nothing to worry
> about, hasn't he?

For idioms like d[foo].append('blah') to work properly, you'd have to 
set the default value every time you access a variable. It can be really 
strange to fill up memory only by apparently accessing values.

> I suspect the proposal really makes sense only if the dict-values are
> of the same type. Filling it with strings, custom objects and other
> stuff and receiving 0 or [] or '' if a key is missing would be a
> surprise - at least for me. Instantiating dict the way I proposed
> indicates type-guards! This is the reason why I want to delay this
> issue and discuss it in a broader context. But I'm also undecided.
> Guidos Python-3000 musings are in danger to become vaporware. "Now is
> better then never"... Therefore +0.

Having duck-typing, we can have things that have common interface but no 
common type. For instance, iterables. I can imagine a list of iterables 
of different types, and a default value of maybe [] or set([]).

-- 
Ciao,
Matteo



More information about the Python-list mailing list