Python 3 使用 IF 或 TRY 测试 None。意想不到的结果

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

我说出乎意料是因为我显然没有正确考虑 Try 和 None。 我来到这里是因为我正在调用一个函数来 return MyVar 的值,然后使用 Trys 进行测试以确保该函数没有 return None。 类似于:

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

我无法获得预期的 TRY 结果。因此,我明确说明了值并再次进行了测试。 通过 IF 测试 None 给出了正确的结果,但是用 TRY 做同样的事情给出了意想不到的结果,这些结果来自下面的代码:

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

Try 是 None 并且 Try 不是 None 两者都是 return True。这怎么可能?关于检查是否已设置值,我遗漏了什么

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" )

try 不关心值是 TrueFalseNone 还是其他任何值。如果没有错误出现,try 执行一段代码,如果出现错误则推迟到 except

See more here