Monday, June 29, 2009

an evil python bug

Not actually a bug in python, more pebkac.

In python there is a built-in dictionary type that you can access with bracket notation (e.g foo['bar']). However, doing this gets you an error when you try and look up a key that's not there. It's a pain to have to keep writing 'if key in dict:...', but luckily, python dictionaries have a built in get() method that will return None instead of erroring out. This is useful if you're looking for duplicates in a list, for example, using dictionaries to remember what you've seen.


Sometimes, though, this behavior isn't enough. What if you want all values to default to 1? Luckily get lets you specify a default value. So if you say dict.get(key, 1) your values will never be None, instead they'll be 1 if there's no key in the dictionary. Right?

Wrong :( get() can still return None, and this was crashing my script. How the hell does dict.get(key, 'blahblahblah') ever return None? The solution eluded me for about an hour and a half on Friday. I wracked my brains with frustration and came up with nothing until a coworker pointed out the blindly obvious. Sucks how it works out that way - the longer you try to debug, the more likely it is to be a retarded basic logic fail that has been staring you in the eye the whole time. I now understand why my office has a ping pong table, nerf guns, and a shuffleboard table, among other distractions - it's because sitting there programming the whole time basically guarantees you'll run into one of these. Also the lack of cubicles - being able to talk to someone and have them look at code with fresh eyes really helps.

Turns out, the value for key in my case was in fact, None. RAGE.


But part of becoming a good developer is learning to be detail-oriented enough so that little shits like these can't trip you up. One down, many more to go...

No comments: