testing for valid reference: obj vs. None!=obs vs. obj is not None

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Sep 5 01:46:51 CEST 2006

alf a écrit :
> Hi,
> I have a reference to certain objects. What is the most pythonic way to 
> test for valid reference:
>     if obj:

Don't do this:

for o in [0, '', [], {}, ()]:
   print obj, bool(obj), obj is None

>     if None!=obs:

In python, assignement is a statement, not an expression, so there's no 
way you could write 'if obj = None' by mistake (-> syntax error). So 
this style is unpythonic. Also, None is a singleton, and identity test 
is way faster than equality test.

>     if obj is not None:

That's the good one.

More information about the Python-list mailing list