Hacker News new | ask | show | jobs
by rlmw 5698 days ago
Upvoted because that's good code reuse in the scenario that you only want to store a default value, and I can see why you replied to the commenter with it. It doesn't necessarily work so well in the scenario where you want to perform some operation if there isn't a value. Or if default needs to be computed. I'm assuming that the idiomatic way of doing this in python would be:

try: value = dict['foo'] except KeyNotFound: value = do_something_interesting() dict['foo'] = value

If you could pass a function in as a default of course this point is moot!

2 comments

See collections.defaultdict in the standard library -- http://docs.python.org/library/collections.html#collections....
> It doesn't necessarily work so well in the scenario where you want to perform some operation if there isn't a value.

No, but that's not what the example he replied to does.