Jonathan
Jonathan

Reputation: 11331

In python, how to test variables that may be other types?

I have a test that makes sure an API return is a success. If it is, it continues, if not, it doesn't. But the problem is, sometimes this result doesn't come back as the right type. Right now I'm testing it with:

if response['result'] == "success": 

But if there's something wrong on the other end, I get a NoneType object back, and then the script crashes. Should I either:

#solution A, nested IFs checking lots of conditions
if type(response['result']) == "string": #not real code
    if response['result'] == "success: 

Or:

#solution B
try: 
    if response['result'] == "success": 
        etc
except: 
    print("Something terrible happened.") 

Or is it better to do something else entirely?

Upvotes: 2

Views: 127

Answers (2)

kojiro
kojiro

Reputation: 77187

Error handling is a perfectly good solution here. If you are expecting a particular type and don't get it, it's definitively an exception.

(You may also wish (defensively) not to assume that the response dict-like object will have a key named result. You can do that with the get method.)

try:
    if response.get('result', '') == "success":
        …
except AttributeError: # Use AttributeError if you use the get method, TypeError if you use regular dict subscripting.
    # response was certainly not successful

Upvotes: 6

J. Owens
J. Owens

Reputation: 852

if response is not None and response['result'] == 'success':
    # Success
else:
    # Failure

Upvotes: 3

Related Questions