Don't be lazy when writing 'if' statements in the Python

Published at 30, July 2008, author art. Tags: python, tips

If you want to check some object is None, don't be lazy, write full statement like this:

res = someFunction()
if res is None:
    print 'blah-minor'

If you write:

if res:
    do_something_useful()

then you can get strange behavior, because not all objects evaluate to True.

For example, try this code:

import xml.etree.ElementTree as ET e = ET.Element('blah') if e: print 'Hello from elementtree'

You'll be surprised.

Comments

Subscribe on this post's comments

permalink

10, November 2008, Āudioslave ᵝ « ... » said:

ага вечные грабли с bool(Element) -> bool(len(Element)) кстати их вроде обещали поправить

If you wish to leave comment, please, identify yourself and then come back to this page.