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

Carl Banks pavlovevidence at gmail.com
Mon Sep 4 17:36:25 EDT 2006


alf wrote:
> Hi,
>
> I have a reference to certain objects. What is the most pythonic way to
> test for valid reference:
>
> 	if obj:
>
> 	if None!=obs:
>
> 	if obj is not None:

If you're checking whether an object is None or not, the third is the
best way.

Some people might say you should use the first: this works sometimes,
but sometimes an object that is not None can be false, in which case
this test will fail.  (I'll give you an example of one place where it
bit me: in ElementTree.  An Element is false if there are no
subelements, thus to test whether a certain element exist, you can't
just say "if aaa.find('bbb')", because a bbb tag exists, it is false
unless it has subelements of its own.  You must instead say "if
aaa.find('bbb') is not None".)

The second test is slower than the first and adds nothing.  Whether
something is None is an identity test; identity tests should use is.


Carl Banks




More information about the Python-list mailing list