return boolean from functions

Preston Landers prestonlanders at
Fri Nov 5 15:16:03 CET 1999

In article <7vsvef$elo$1 at>,
  Preston Landers <prestonlanders at> wrote:

> Alternatively, you can do this:
> TRUE=1
> 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

anders, I noticed your other message about returning true for success
and false for fail.  That's fine if that works for you, but FYI the
convention in Unix[1] is generally to return false for success, and true
for an error condition.  This way the exact condition can be contained
in the return value, such as:

def foo():
   return "foo is bad"

The code that calls this will look like this:

result = foo()
if result:
   print "Foo failed and said: %s" % result
   raise SystemExit(1)

# continue on merry way


[1] Assuming you think Unix is conventional

Sent via
Before you buy.

More information about the Python-list mailing list