Using try vs if in python

Posted by artdanil on Stack Overflow See other posts from Stack Overflow or by artdanil
Published on 2009-12-02T20:58:37Z Indexed on 2010/05/11 21:34 UTC
Read the original article Hit count: 153

Filed under:
|

Is there a rationale to decide which one of try or if constructs to use, when testing variable to have a value?

For example, there is a function that returns either a list or doesn't return a value. I want to check result before processing it. Which of the following would be more preferable and why?

result = function();
if (result):
    for r in result:
        #process items

or

result = function();
try:
    for r in result:
        #process items
except TypeError:
    pass;

Related discussion:

Checking for member existence in Python

© Stack Overflow or respective owner

Related posts about python

Related posts about best-practices