Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a defaultdict safe for unexpecting clients?

Several times (even several in a row) I've been bitten by the defaultdict bug: forgetting that something is actually a defaultdict and treating it like a regular dictionary.

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.

like image 660
user354193 Avatar asked Jun 13 '10 10:06

user354193


2 Answers

You may still convert it to an normal dict.

d = collections.defaultdict(list)
d = dict(d)
like image 55
evilpie Avatar answered Oct 14 '22 17:10

evilpie


use different idiom:

if 'key' not in d:
    print "Sorry, no dice!"
like image 42
SilentGhost Avatar answered Oct 14 '22 18:10

SilentGhost