Search code examples
pythoncomparison

'variable' or 'variable is not None'


Variable = None

Is there any difference between these three in a specific scenario ? if there is no difference which one is more suitable to use?

if Variable:
 print "Hello world"

and

if Variable is not None:
 print "Hello world"

and

if Variable != None:
 print "Hello world"

are same in case of None Variable ?


Solution

  • Is there any difference between these three in a specific scenario ?

    The first asks whether the variable is anything falsy. This test will fail for all kinds of things besides NoneFalse, 0, any empty sequence, etc.

    The second asks whether it's the magic singleton constant None. This will fail only for None itself.

    The third asks whether it's anything that considers itself equal to None. This will fail for, say, Holder(None), where Holder is a wrapper class whose instances compare equal to whatever they're holding. Or, to give a less realistic but shorter to code exmaple:

    class Stupid(object):
        def __ne__(self, other):
            return False
    Variable = Stupid()
    

    The last one is rarely useful; in fact, if you ever think you might need to check == None or != None, and you haven't specifically been creating transparent-wrapper classes or anything like that, you probably actually wanted is None or is not None. But the other two are both very useful and common.

    if there is no difference which one is more suitable to use?

    Well, there is a difference, and which one is more suitable depends on the specific use.

    At the end of the question, it seems like you might be asking whether there's any difference in the specific case where Variable is definitely None. In that case, of course there is no functional difference between the three.* All of them are guaranteed to be false, and therefore do nothing. Which means there's also no difference between any of the three and writing no code at all. Which is a lot simpler, more readable, and faster.

    * There is a performance difference—the first one doesn't have to LOAD_CONST the None, or call a comparison operator. And, even if you've somehow managed to rebind None or change the value of the None constant (maybe by stomping all over the heap with ctypes?), the first one is more likely to still work. But neither of these is ever going to matter—and, if they do, again, no code at all will be even faster and more reliable.