by csense · 12y ago · 0 comments
E.g. something like:
try:
something = myfunc(d['x'])
except ValueError:
something = None
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:
something = d.get('x')
if something is not None:
something = myfunc(something)
Or if dictionary may potentially contain None values: if 'x' in d:
something = myfunc(d['x'])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)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 something = d.get('x', default) try:
open(FILE)
except IOError:
it failed something = myfunc(d['x']) if 'x' in d else NoneIn any event don't optimize prematurely and use a profiler rather than guessing if performance is an issue. ;-)