Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'variable' or 'variable is not None' [duplicate]

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 ?

like image 965
NIlesh Sharma Avatar asked Mar 27 '13 05:03

NIlesh Sharma


People also ask

How do you know if a variable is not None?

Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).

Is None vs if not?

Both "if x" and "if x is none" are not the same. If you run the statement "if x:" checks whether x is assigned or not. If you execute the statement "if x is not none", is operator checks whether x is none or not. If you are still confused, Assign the values x = none, x = [], and x = 21 and run the following code.

What does not None mean in Python?

It's often used as the default value for optional parameters, as in: def sort(key=None): if key is not None: # do something with the argument else: # argument was omitted. If you only used if key: here, then an argument which evaluated to false would not be considered.

How do you check if a variable is None in Python?

Use the is operator to check if a variable is None in Python, e.g. if my_var is None: . The is operator returns True if the values on the left-hand and right-hand sides point to the same object and should be used when checking for singletons like None .


2 Answers

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.

like image 170
abarnert Avatar answered Sep 22 '22 00:09

abarnert


not x will be true if x is None, False, [], {}, etc.

x is not None will always be True, unless a variable is actually None.

Edit:

This is of practical importance, whenever you want to check if a variable is actually set to a proper value. Otherwise you can run into problems. For example, if you want to evaluate a list of items and do:

if not x:

to check if a list was provided, then the condition will trigger on an empty list, which may still be a valid input. So in that case, you'd like to check with

if x is not None:

to allow empty lists as valid inputs, but still check the case that no list at all was provided.

The None value as such is comparable to a null or nil value in certain languages. It's a placeholder for the lack of a value in a defined variable (if it is undefined, it will throw a NameError). That's why the None value is used as a default value in some cases:

>>> def foo():
...     pass
...
>>> x = foo()
>>> x is None
True

It's also frequently used as a default value for optional variables:

>>> def foo(bar=None):
...     if bar is None:
...         print('No argument passed.')
...     else:
...         print('Variable bar: %s' % str(bar))
...
>>> foo(0)
Variable bar: 0
>>> foo()
No argument passed.

This way, 0 is still a valid value, that would evaluate to False if checked with if not bar:.

like image 34
Stjepan Bakrac Avatar answered Sep 23 '22 00:09

Stjepan Bakrac