I was coding some Python, and I kept ending up with code that looked like:
try:Translating that little idiom into a function is hard. Every single use of  might result in a KeyError. I could use .get() on each, but that's painful. Similarly, managing a hierarchy of defaultdicts is a bit painful too; the values in my dicts are a mix of ints and other nested dicts.
count = d['a']['b']['c']
count = 0
The question is, how do you put the try / except part into a function, and use d['a']['b']['c'] as an argument? After all, if you call f(d['a']['b']['c']), and d['a']['b']['c'] results in a KeyError, f will never even be called.
The solution, if you haven't guessed by now, is to wrap it in a lambda. Hence, I have a function:
def default0(f):Here's how you use it:
"""Return f(), or 0 if it raises a KeyError."""
(Now, of course you could get really fancy with default0 such as configuring which exceptions it will catch and what value it should return. However, then I'd either have to pass those arguments or use the functools.partial function. I think default0 is simple enough, short enough, and local enough to my problem that I didn't bother.)