[Python-Dev] defaultdict proposal round three
Raymond Hettinger
raymond.hettinger at verizon.net
Mon Feb 20 17:35:35 CET 2006
[GvR]
> I'm not convinced by the argument
> that __contains__ should always return True
Me either. I cannot think of a more useless behavior or one more likely to have
unexpected consequences. Besides, as Josiah pointed out, it is much easier for
a subclass override to substitute always True return values than vice-versa.
> Alternative A: add a new method to the dict type with the semantics of
> __getattr__ from the last proposal
Did you mean __getitem__? If not, then I'm missing what the current proposal
is.
>, using default_factory if not None
> (except on_missing is inlined). This avoids the discussion about
> broken invariants, but one could argue that it adds to an already
> overly broad API.
+1
I prefer this approach over subclassing. The mental load from an additional
method is less than the load from a separate type (even a subclass). Also,
avoidance of invariant issues is a big plus. Besides, if this allows
setdefault() to be deprecated, it becomes an all-around win.
> - Even if the default_factory were passed to the constructor, it still
> ought to be a writable attribute so it can be introspected and
> modified. A defaultdict that can't change its default factory after
> its creation is less useful.
Right! My preference is to have default_factory not passed to the constructor,
so we are left with just one way to do it. But that is a nit.
> - It would be unwise to have a default value that would be called if
> it was callable: what if I wanted the default to be a class instance
> that happens to have a __call__ method for unrelated reasons?
> Callability is an elusive propperty; APIs should not attempt to
> dynamically decide whether an argument is callable or not.
That makes sense, though it seems over-the-top to need a zero-factory for a
multiset.
An alternative is to have two possible attributes:
d.default_factory = list
or
d.default_value = 0
with an exception being raised when both are defined (the test is done when the
attribute is created, not when the lookup is performed).
Raymond
More information about the Python-Dev
mailing list