-
Notifications
You must be signed in to change notification settings - Fork 471
defaultdict is danger
Simply looking at a defaultdict
dictionary can change its value and break things.
Suppose you pass your defaultdict
to a function that says:
try:
return d[name]
except KeyError:
pass
It will add an empty value to the dictionary unexpectedly.
I'm against defaultdict
nearly always, and that's because you get a thing that looks like a dict and can get passed around like a dict but isn't a dict in a very important way.
I see code snippets like collection[key]
hundreds of times every day. Nearly always, this snippet does not change collection
and raises an exception if key
is not in collection
.
If this is not true, I have to stop and think about it, which wastes my time, but sometimes I'll miss that, and perhaps make a mistake.
Using defaultdict
is a little less work for the writer, but considerable more effort for the reader. But code is written once and read a hundred times.
Down with defaultdict
!