How do I make a defaultdict safe for unexpecting clients?
- by ~miki4242
Several times (even several in a row) I've been bitten by the defaultdict bug.
d = defaultdict(list)
...
try:
v = d["key"]
except KeyError:
print "Sorry, no dice!"
For those who have been bitten too, the problem is evident: when d has no key 'key', the v = d["key"] magically creates an empty list and assigns it to both d["key"] and v instead of raising an exception. Which can be quite a pain to track down if d comes from some module whose details one doesn't remember very well.
I'm looking for a way to take the sting out of this bug. For me, the best solution would be to somehow disable a defaultdict's magic before returning it to the client.