Jeff Widman
Jeff Widman

Reputation: 23502

Why does the code inside this "if" statement still run?

I have the following python function:

api_function:
    try:
        # api query
    except:
        # api error #1
        return "api error 1"
    except:
        # api error #2
        return "api error 2"
    else: 
        return api_data_dict

I want to run this function, and if there's no error, parse the data returned from the API:

for call in api_call_list:
    raw_api_data = api_function(access_token)
        if raw_api_data != 'api error 1' or 'api error 2':
            page_name = raw_api_data['name']
            # process api data

When I run the code, it runs fine as long as the API is working. However, when the API hits an error, the if statement doesn't seem to catch the string--instead, I get the traceback:

Traceback (most recent call last):
  File "api_retriever.py", line 4, in <module>
    page_name = raw_api_data['name']
TypeError: string indices must be integers, not str

Why isn't my if statement catching the error string returned by my api_function and preventing line 4 from even running?

Upvotes: 0

Views: 96

Answers (2)

starrify
starrify

Reputation: 14751

This line of your code:

if raw_api_data != 'api error 1' or 'api error 2':

is actually interpreted as

if (raw_api_data != 'api error 1') or ('api error 2'):

and in Python a non-empty string would always evaluate to True.

You shall use:

if (raw_api_data != 'api error 1') and (raw_api_data != 'api error 2'):

or

if not raw_api_data in ('api error 1', 'api error 2'):

Upvotes: 4

Mailerdaimon
Mailerdaimon

Reputation: 6080

Or is Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (source)

Use this instead:

if (raw_api_data != 'api error 1') and (raw_api_data != 'api error 2'):

Upvotes: 2

Related Questions