Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 947
Jonathan Avatar asked Mar 09 '26 14:03

Jonathan


2 Answers

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
like image 113
kojiro Avatar answered Mar 12 '26 02:03

kojiro


if response is not None and response['result'] == 'success':
    # Success
else:
    # Failure
like image 38
J. Owens Avatar answered Mar 12 '26 03:03

J. Owens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!