[Python-Dev] Proposal: defaultdict (original) (raw)

Adam Olsen rhamph at gmail.com
Sat Feb 18 02:29:34 CET 2006


On 2/17/06, "Martin v. Löwis" <martin at v.loewis.de> wrote:

Adam Olsen wrote: > You could pass a float in as well. But if the function is documented > as taking a dict, and the programmer expects a dict.. that now has to > be changed to "dict without a default". Or they have to code > defensively since d[key] may or may not raise KeyError, so they must > avoid depending on it either way.

Can you give an example of real, existing code that will break if a such a dict is passed?

I only got halfway through the "grep KeyError" results, but..

Demo/metaclass/Meta.py:55 Demo/tkinter/guido/AttrDialog.py:121 # Subclasses override self.classes Lib/ConfigParser.py:623 Lib/random.py:315 Lib/string.py:191 Lib/weakref.py:56 # Currently uses UserDict but I assume it will switch to dict eventually

And the pièce de résistance.. Doc/tools/anno-api.py:51

It has this: try: info = rcdict[s] except KeyError: sys.stderr.write("No refcount data for %s\n" % s) else: ... rcdict is loaded from refcounts.load(). refcounts.load() calls refcounts.loadfile(), which has this (inside a loop): try: entry = d[function] except KeyError: entry = d[function] = Entry(function) A prime candidate for a default.

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.

-- Adam Olsen, aka Rhamphoryncus



More information about the Python-Dev mailing list