'if name is not None:' v. 'if name:'

Matimus mccredie at gmail.com
Tue Jul 15 16:00:52 EDT 2008


On Jul 15, 12:44 pm, "Victor Noagbodji" <noagbodjivic... at gmail.com>
wrote:
> >>what's the difference between these two statement?
> >one checks if the given object is not None, the other checks if it's a true value:
> >http://docs.python.org/ref/Booleans.html#Booleans
> >>And which one should one use?
> >depends on what you want to test for, of course.
>
> ></F>
>
> Well that's exactly why I'm asking. Since None returns False in if
> statements. Why do people use if name is not None: instead of simply
> writing if not name?
>
> --
> NOAGBODJI Paul Victor

1. If you want to distinguish between None and something else that
evaluates to False.
2. Speed, "is not" is checking identity of the objects. That can be
(and usually is) much quicker than checking whether or not it
evaluates to True. Checking the boolean value calls the "__nonzero__"
method of an object. That method could be user defined and very
complex.

In general there are many cases where you use "None" as a placeholder
(similar to NULL in C/C++). The best practice is to always compare
identity with None.

Matt



More information about the Python-list mailing list