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.
You may still convert it to an normal dict.
d = collections.defaultdict(list)
d = dict(d)
use different idiom:
if 'key' not in d:
print "Sorry, no dice!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With