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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Jul 29 19:30:12 EDT 2008


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

> On Jul 29, 5:15 am, Heiko Wundram <modeln... at modelnine.org> 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:
    do_something


# Carl's so-called "simple explicit tests" applied to polymorphic code:
try:
    # 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:
        do_something
except AttributeError:
    # not a sequence or mapping, maybe it's a number of some sort
    try:
        int(x)
    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):
            do_something
    else:
        if x != 0:
              do_something


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

if bool(x):
    do_something

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

if x:
    do_something



-- 
Steven



More information about the Python-list mailing list