Search code examples
pythontry-catchexcept

Python 3 Testing for None with IF or TRY. Unexpected Results


I say unexpected because I am clearly not thinking about Try and None correctly. I got here because I was calling a function to return a value for MyVar, and then testing with Trys to ensure the function did not return None. Something like:

def Myfunct():
    return "Some_URL"
MyVar = Myfunct()
try:
    MyVar is not None:
    pass

I could not get the expected TRY result. So I explicitly stated values and tested again. Testing for None via IF gives the right results, but doing the same with TRY gives unexpected results, which come from the code below:

Type of My_Var is: <class 'str'> with value:  Some_URL
IF is None: False
IF is not None: True
TRY is None: True
TRY is not None: True

Both Try is None and Try is not None both return True. How is that possible? What am I missing about checking if a value has been set

My_Var = None
My_Var = "Some_URL"
print ("Type of My_Var is:", type(My_Var), "with value: ", My_Var)

if My_Var is None:
    print ("IF is None: True")
else:
    print ("IF is None: False")

if My_Var is not None:
    print ("IF is not None: True")
else:
    print ("IF is not None: False")    

try:
    My_Var is None
    print ("TRY is None: True" )
    pass

except Exception as e:
    print ("TRY is None: False" )

try:
    My_Var is not None
    print ("TRY is not None: True" )
    pass

except Exception as e:
    print ("TRY is not None: False" )

Solution

  • try doesn't care about whether a value is True, False, None, or anything else. try executes a block of code if no errors arise, and defers to except if errors do arise.

    See more here