Raymond Hettinger <rhettin...@users.sourceforge.net> added the comment:

[Łukasz Langa]

> __missing__ didn't appear to be the one obvious way to anyone.

Two thoughts:

* There is part of the Zen that says that way may not be obvious unless your 
Dutch.  In this case,  __missing__ was the API designed by Guido to handle the 
problem.  If it isn't obvious, it is up to us to popularize the idiom in talks, 
in tutorials, in newsgroup discussions, etc.  And FWIW, it is not unprecedented 
-- Lua's dicts have a similar hook and most of the interesting programming in 
Lua relies on it.

* The __missing__ method should not be considered a dark corner of Python.  
Unlike the copy module, pickling, of weakrefs, it is not tucked away in the 
library.  The missing method is part of the basic API for one of Python's most 
fundamental objects.  If someone is going to be a Python programmer, they must 
at least learn about dicts, lists, strings, and tuples.

> then again I've used "", [] and set() numerous times. 
> Adding zerodict, stringdict, listdict, setdict is 
> obviously absurd.

Looking at those examples, you're probably already aware that the list and set 
versions are already served by defaultdict(), and that it would be basic (and 
probably common) mistake to accidentally use [] in your proposed constant dict.

A constant version of the defaultdict only makes sense with immutables such as 
numbers, strings, and tuples.  The common case would be the number zero and we 
have Counter() for that.  So, you're left with very few use cases and with a 
hazard for users who may write: f = fallback_dict([]).   

> 4. I cannot come up with another typical integer value 
> that would be useful

FWIW, the Counter class *is* a ZeroDict.  It has a few extra methods but is 
basically a dict with __missing__ set to return zero.

> ... then I'm +1 on correcting the docs in terms of 
> __missing__ and leaving the implementation as is.

Thank you.  Will reclassify this as a doc issue.



[Éric Araujo]
> 2) Add examples of giving dict or int to 
> collections.defaultdict to get {} or 0 as default value.

Those examples have been there since day one.

[Michael Foord]
> I'm sure the documentation could be improved to highlight
> __missing__ though.

I'll add another example and perhaps include on in the tutorial.

> It's almost always the case that documentation can be improved. :-)

Getting people to read it is another story ;-)

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue10533>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to