return boolean from functions

Michael Hudson mwh21 at cam.ac.uk
Fri Nov 5 10:51:00 EST 1999


Preston Landers <prestonlanders at my-deja.com> writes:

> In article <7vsvef$elo$1 at nnrp1.deja.com>,
>   Preston Landers <prestonlanders at my-deja.com> wrote:
> 
> > Alternatively, you can do this:
> >
> > TRUE=1
> > FALSE=0
> >
> > def foo(bar):
> >   if bar == "spam":
> >      return TRUE
> >   else:
> >      return FALSE
> 
> Sorry to follow up my own article, but it should be noted that the way I
> have it above will cause a namespace lookup (TRUE and FALSE) every time
> you call foo() (aside from the usual function overhead.)  So, if you are
> calling this function from a critical loop, you might want to avoid the
> namespace lookup and just return None or 1.  Also note that the word
> "None" is optional when you want to return false; you can do this:
> 
>   if foo:
>      return  # will return None

Umm, `return None' causes a name lookup too, and one that will wind up
getting resolved in __builtins__ - the searching place of last resort,
so

def f1():
    return None

will be slower than

FALSE = 0
def f2():
    return FALSE

which will be slower than

def f3():
    return 0

which will be about the same as

def f4():
    return

which wont be much different to

def f5():
    pass

which in turn will be ever-so-slightly slower than

def f6(None=None):
    return None

(which I bet you didn't expect!)

It's worth noting (unlike the above) that the differences involved are
very very small, so you should go for the one which expresses what you
actually mean, which imho is most likely to be f1 or f3.

there's-more-than-one-way-to-say-nothing-ly y'rs
Michael




More information about the Python-list mailing list