Not to counter your point, but I would like to quote from PEP8 here:
Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.
Yes:
try:
value = collection[key]
except KeyError:
return key_not_found(key)
else:
return handle_value(value)
No: try:
# Too broad!
return handle_value(collection[key])
except KeyError:
# Will also catch KeyError raised by handle_value()
return key_not_found(key)
Re:Python Idioms [pdf]
by yetanotherphd on Thursday January 30, 2014 @10:29PM
(#7155064)
These two comments together make a lot of sense.
When your try block is a single lookup, you might as well use an if statement or get. However, when the 'absolute minimum' is nontrivial try/except is still a good option, e.g.
try:
name = employee['name']
first_name = name['first_name']
last_name = name['last_name']
except KeyError:
print "Bad employee data"
return
Re:Python Idioms [pdf]
by eliteraspberrie on Thursday January 30, 2014 @12:20PM
(#7151852)
Also note the second argument to the get method specifies the default value to return in case of a KeyError:
something = d.get('x', default)
Re:Python Idioms [pdf]
by middleclick on Thursday January 30, 2014 @12:12PM
(#7151778)
While not disagreeing with your case, there are some cases where I try to follow this rule because in most of those cases, I would expect that there is no exception and if there is, then catch it.
try:
open(FILE)
except IOError:
it failed
Re:Python Idioms [pdf]
by drakeandrews on Thursday January 30, 2014 @12:22PM
(#7151863)
That example would surely be better as:
something = myfunc(d['x']) if 'x' in d else NoneIn this form you perform the lookup twice: once to test 'x' in d and then again to actually get the value d['x']. Try clauses in Python are very inexpensive if they pass (don't raise an exception), so often the try..except version would be preferable.
In any event don't optimize prematurely and use a profiler rather than guessing if performance is an issue. ;-)
Doesn't this go against the Pythonic notion of handling exceptions rather than "looking before you leap"?
That looks like perl.
Re:Python Idioms [pdf]
by GFK_of_xmaspast on Friday January 31, 2014 @01:08AM
(#7155562)
what's going to happen in your second example if somebody gives you a defaultdict instead of a regular dict for d.
E.g. something like:
The programmer's intent is probably to only catch errors in the key lookup d['x'], but if there is some bug in the implementation of myfunc() or any of the functions called by myfunc() which causes a ValueError to unintentionally be raised, it will be caught by the except.For dictionary lookups specifically, get() is usually preferable:
Or if dictionary may potentially contain None values: