Boolean tests [was Re: Attack a sacred Python Cow]

Steven D'Aprano steve at
Wed Jul 30 01:30:12 CEST 2008

On Tue, 29 Jul 2008 10:30:43 -0700, Carl Banks wrote:

> On Jul 29, 5:15 am, Heiko Wundram <modeln... at> wrote:
>> I can't dig up a simple example from code I wrote quickly, but because
>> of the fact that explicit comparisons always hamper polymorphism
> I'm not going to take your word for it.  Do you have code that
> demonstrates how "if x" improves polymorphism relative to simple
> explicit tests?

On the rapidly decreasing chance that you're not trolling (looking more 
and more unlikely every time you post):

# The recommended way:
if x:

# Carl's so-called "simple explicit tests" applied to polymorphic code:
    # could be a sequence or mapping?
    # WARNING: must do this test *before* the number test, otherwise
    # "if [] != 0" will return True, leading to the wrong branch being
    # taken.
    if len(x) != 0:
except AttributeError:
    # not a sequence or mapping, maybe it's a number of some sort
    except TypeError:
        # not convertable to numbers
        # FIXME: not really sure what to do here for arbitrary types
        # so fall back on converting to a boolean, and hope that works
        if bool(x):
        if x != 0:

But wait... that can be re-written as follows:

if bool(x):

and that can be re-written without the call to bool:

if x:


More information about the Python-list mailing list