Better writing in python

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Oct 24 17:16:10 CEST 2007


cokofreedom at gmail.com a écrit :
(snip)
> Anyone know why towards arg is True and arg is False, arg is None is
> faster than arg == None ...

Perhaps reading about both the meaning of the 'is' operator might help ? 
  the expression 'arg is True' will only eval to true if 'id(arg) == 
id(True)'. Now Python objects does have a truth value by themselves. So 
an object can eval to false in a boolean test *without* being the False 
object itself.

For the record, True and False are late additions to the language - at 
first, it only had truth values of objects, basically defined as 'empty 
sequences and containers, numeric zeros and None are false, anything 
else is true unless either:
- the class implements the __len__ magic method and len(obj) == 0
- the class implements the magic method __non_zero__ (IIRC) and this 
obj.__non_zero__ returns false.

So the common idiom is to test the truth value of an object, which is 
expressed as "if obj: " - using 'if obj == True:' being redundant and 
'if obj is True:' usually not what you want.

wrt/ None: Since being None is not the same thing as being false (even 
if the first imply the second) - there may be cases where you want to 
distinguish between an object with a false truth value from the None 
object itself - so you can't just use 'if not obj:'. Now since None is 
garanteed to be a singleton, it defines it's __cmp__ (the magic method 
for '==') as an identity test. So directly using the identity test is 
faster since it yields the exact same result as the equality test 
without the overhead of the additional method call.





More information about the Python-list mailing list