It appears that "if x" is almost like short-hand for the longer "if x is not None" syntax. Are they functionally identical or are there cases where for a given value of x the two would evaluate differently?
I would assume the behavior should also be identical across Python implementations - but if there are subtle differences it would be great to know.
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 checks to see if the object is the same object, while == just checks if they are equivalent. But since there is only one None , they will always be the same, and is will return True.
The test is designed to check whether or not x was assigned to, or not. When you do if x is None , you call the operator is , which checks the identity of x . None is a singleton in Python and all None values are also the exact same instance. When you say if x , something different happens.
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.
In the following cases:
test = False test = "" test = 0 test = 0.0 test = [] test = () test = {} test = set() the if test will differ:
if test: #False if test is not None: #True This is the case because is tests for identity, meaning
test is not None is equivalent to
id(test) == id(None) #False therefore
(test is not None) is (id(test) != id(None)) #True
The former tests trueness, whereas the latter tests for identity with None. Lots of values are false, such as False, 0, '', and None, but only None is None.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With