Python Language Use truth value testing


Python will implicitly convert any object to a Boolean value for testing, so use it wherever possible.

# Good examples, using implicit truth testing
if attr:
    # do something

if not attr:
    # do something

# Bad examples, using specific types
if attr == 1:
    # do something

if attr == True:
    # do something

if attr != '':
    # do something

# If you are looking to specifically check for None, use 'is' or 'is not'
if attr is None:
    # do something

This generally produces more readable code, and is usually much safer when dealing with unexpected types.

Click here for a list of what will be evaluated to False.