DEV Community

Discussion on: Dead Simple Python: Errors

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

It's a good point - you should always measure for your specific scenario.

The except is supposed to be the "exceptional" scenario, rather than the rule. In general, the try should succeed several times more often than it fails. Contrast that with the if...else (ask permission) scenario, where we perform the lookup every time, the try...except scenario actually winds up being the more efficient approach in most cases. (See this StackOverflow answer.)

To put that another way, if you imagine that just the if...else and try...except structures by themselves are roughly identical in performance, at least typical scenarios, it is the conditional statement inside of the if() that is the point of inefficiency.

I'm oversimplifying, of course, but this can at least get you in the ballpark. if(i % 2 == 0) is going to be pretty inexpensive, and would succeed only 50% of the time in any given sequential, so that would be a case where we'd almost certainly use an if...else for our flow control; try...except would be too expensive anyway! By contrast, the dictionary lookup is quite a bit more expensive, especially if it succeeds eight times more than it fails. If we know from our data that it will fail more than succeed, however, an "ask permission" approach may indeed be superior.

At any rate, yes, measure, and consider the costs of your particular scenario.

P.S. As I mentioned in the article, of course, the collections.defaultdict would be considered superior to both try...except and if...else in the example scenario.