3 ms·
That example would surely be better as: something = myfunc(d['x']) if 'x' in d else None
by drakeandrews 13y ago
That example would surely be better as:
something = myfunc(d['x']) if 'x' in d else None
- prawks 13y agoDoesn't this go against the Pythonic notion of handling exceptions rather than "looking before you leap"?
- wiredfool 13y agoThat looks like perl.
- calroc 13y agoIn 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. ;-)