How do I make a defaultdict safe for unexpecting clients?

Posted by ~miki4242 on Stack Overflow See other posts from Stack Overflow or by ~miki4242
Published on 2010-06-13T10:05:04Z Indexed on 2010/06/13 10:12 UTC
Read the original article Hit count: 167

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about python

Related posts about default-value