I’ve seen several examples of code like this:
if not someobj: #do something
But I’m wondering why not doing:
if someobj == None: #do something
Is there any difference? Does one have an advantage over the other?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In the first test, Python try to convert the object to a
boolvalue if it is not already one. Roughly, we are asking the object : are you meaningful or not ? This is done using the following algorithm :If the object has a
__nonzero__special method (as do numeric built-ins,intandfloat), it calls this method. It must either return aboolvalue which is then directly used, or anintvalue that is consideredFalseif equal to zero.Otherwise, if the object has a
__len__special method (as do container built-ins,list,dict,set,tuple, …), it calls this method, considering a containerFalseif it is empty (length is zero).Otherwise, the object is considered
Trueunless it isNonein which case, it is consideredFalse.In the second test, the object is compared for equality to
None. Here, we are asking the object, ‘Are you equal to this other value?’ This is done using the following algorithm :If the object has a
__eq__method, it is called, and the return value is then converted to aboolvalue and used to determine the outcome of theif.Otherwise, if the object has a
__cmp__method, it is called. This function must return anintindicating the order of the two object (-1ifself < other,0ifself == other,+1ifself > other).Otherwise, the object are compared for identity (ie. they are reference to the same object, as can be tested by the
isoperator).There is another test possible using the
isoperator. We would be asking the object, ‘Are you this particular object?’Generally, I would recommend to use the first test with non-numerical values, to use the test for equality when you want to compare objects of the same nature (two strings, two numbers, …) and to check for identity only when using sentinel values (
Nonemeaning not initialized for a member field for exemple, or when using thegetattror the__getitem__methods).To summarize, we have :