News for hackers. Stuff that matters.
Re:Isaacs: try/catch is an anti-pattern by phzbOx on Monday November 14, 2011 @08:48AM (#3233895)
I think the best is a little of both ways. For instance in python:

  x = some_dict['meh']
Will raise if 'meh' doesn't exist. If you believe that 'meh' should be there in your program, it's fine to 'let it raise an exception'.

However, if 'meh' could be there, it's better to use an error style such as:

  x = some_dict.getDefault('meh', 'some-neutral-value')
And continue without raising because there's no need to raise as there's nothing exceptional here.

Ideally, raising an exception should have the meaning "Hey, something is wrong here and I don't know what to do next". And someone in the call hierarchy would handle this and say "Oh, the connection stopped.. that's why it's not working. I'll reconnect and call you again".

And note that this "parent handling" might be way higher than where the problem occurred..

Re:Isaacs: try/catch is an anti-pattern by gaius on Monday November 14, 2011 @09:05AM (#3233948)
Re:Isaacs: try/catch is an anti-pattern by TylerE on Monday November 14, 2011 @09:11AM (#3233976)
No he doesn't. defaultdict provides a default value for ALL missing values. His approach allows him to target one key in particular, and is a very common python idiom.
Re:Isaacs: try/catch is an anti-pattern by gaius on Monday November 14, 2011 @09:45AM (#3234122)
I'm confused - where does that come from?

  >>> x.getDefault(1, 'Que?')

  Traceback (most recent call last):
    File "<pyshell#2>", line 1, in <module>
      x.getDefault(1, 'Que?')
  AttributeError: 'dict' object has no attribute 'getDefault'
Re:Isaacs: try/catch is an anti-pattern by TylerE on Monday November 14, 2011 @09:55AM (#3234164)
Because it's actually (somewhat confusingly, called setdefault).

    >>> a = {1:'foo',2:'blah'}
    >>> a.setdefault(1,'default')
    'foo'
    >>> a.setdefault(4,'default')
    'default'
    >>> a
    {1: 'foo', 2: 'blah', 4: 'default'}
This actually updates the underlying datastructure. Very handy when you want to deal with nested structures, since you can do something like:

    matches.setdefault(keyword,[]).append(s)
This will append s to the list in matches[keyword] if it exists, or set matches[keyword] to [] and then append.
Re:Isaacs: try/catch is an anti-pattern by phzbOx on Monday November 14, 2011 @09:49AM (#3234141)
Wops, you both are right, thanks for pointing it out. I meant to say dict.get, i.e.

  {'a':1}.get('b',5)