[Python-Dev] Proposal: defaultdict

"Martin v. Löwis" martin at v.loewis.de
Sat Feb 18 09:08:00 CET 2006


Adam Olsen wrote:
> Demo/metaclass/Meta.py:55

That wouldn't break. If you had actually read the code, you would have
seen it is

        try:
            ga = dict['__getattr__']
        except KeyError:
            pass

How would it break if dict had a default factory? ga would get the
__getattr__ value, and everything would be fine. The KeyError is
ignored, after all.

> Demo/tkinter/guido/AttrDialog.py:121  # Subclasses override self.classes

Hmm

            try:
                cl = self.classes[c]
            except KeyError:
                cl = 'unknown'

So cl wouldn't be 'unknown'. Why would that be a problem?


> Lib/ConfigParser.py:623

               try:
                    v = map[var]
                except KeyError:
                    raise InterpolationMissingOptionError(
                        option, section, rest, var)

So there is no InterpolationMissingOptionError. *Of course not*.
The whole point would be to provide a value for all interpolation
variables.

> Lib/random.py:315

This entire functions samples k elements with indices between 0
and len(population). Now, people "shouldn't" be passing dictionaries
in in the first place; that specific code tests whether there
valid values at indices 0, n//2, and n. If the dictionary
isn't really a sequence (i.e. if it doesn't provide values
at all indices), the function may later fail even if it passes
that test.

With a default-valued dictionary, the function would not fail,
but a large number of samples might be the default value.

> Lib/string.py:191

Same like ConfigParser: the intperpolation will always succeed,
interpolating all values (rather than leaving $identifier in the
string). That would be precisely the expected behaviour.

> Lib/weakref.py:56  # Currently uses UserDict but I assume it will
> switch to dict eventually

Or, rather, UserDict might grow the on_missing feature as well.

That is irrelevant for this issue, though:

        o = self.data[key]()
        if o is None:
            raise KeyError, key      # line 56
        else:
            return o

So we are looking for lookup failures in self.data, here:
self.dict is initialized to {} in UserDict, with no
default factory. So there cannot be a change in behaviour.


> Perhaps the KeyError shouldn't ever get triggered in this case, I'm
> not sure.  I think that's besides the point though.  The programmer
> clearly expected it would.

No. I now see your problem: An "except KeyError" does *not* mean
that the programmer "clearly expects it will" raise an KeyError.
Instead, the programmer expects it *might* raise a KeyError, and
tries to deal with this situation.

If the situation doesn't arise, the code continue just fine.

Regards,
Martin


More information about the Python-Dev mailing list