[Python-Dev] Proposal: defaultdict

Michael Urman murman at gmail.com
Sun Feb 19 17:23:15 CET 2006


On 2/19/06, Josiah Carlson <jcarlson at uci.edu> wrote:
> My post probably hasn't convinced you, but much of the confusion, I
> believe, is based on Martin's original belief that 'k in dd' should
> always return true if there is a default.  One can argue that way, but
> then you end up on the circular train of thought that gets you to "you
> can't do anything useful if that is the case, .popitem() doesn't work,
> len() is undefined, ...".  Keep it simple, keep it sane.

A default factory implementation fundamentally modifies the behavior
of the mapping. There is no single answer to the question "what is the
right behavior for contains, len, popitem" as that depends on what the
code that consumes the mapping is written like, what it is attempting
to do, and what you are attempting to override it to do. Or, simply,
on why you are providing a default value. Resisting the temptation to
guess the why and just leaving the methods as is seems  the best
choice; overriding __contains__ to return true is much easier than
reversing that behavior would be.

An example when it could theoretically be used, if not particularly
useful. The gettext.install() function was just updated to take a
names parameter which controls which gettext accessor functions it
adds to the builtin namespace. Its implementation looks for "method in
names" to decide. Passing a default-true dict would allow the future
behavior to be bind all checked names, but only if __contains__
returns True.

Even though it would make a poor base implementation, and these
effects aren't a good candidate for it,  the code style that could
best leverage such a __contains__ exists.

Michael
--
Michael Urman  http://www.tortall.net/mu/blog


More information about the Python-Dev mailing list