boolean from a function

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Dec 13 18:37:08 EST 2011


On Tue, 13 Dec 2011 16:24:05 +0000, Andrea Crotti wrote:

> I'm not sure for how long I had this bug, and I could not understand the
> problem.
> 
> I had a function which would return a boolean
> 
> def func_bool():
>      if x:
>          return True
>      else: return False

x is a global? Poor design. But in any case, instead of an explicit 
if...else block, the canonical way to convert an arbitrary object to True/
False is with bool:

def func_bool():
    return bool(x)

But you don't need it. See below.


> Now somewhere else I had
> 
> if func_bool:
>      # do something

That would be better written as:

if x:
   ...

since func_bool always refers to x, it is just a needless level of 
indirection that doesn't buy you anything.


> I could not quite understand why it was always true, until I finally
> noticed that the () were missing.
> Is there some tool to avoid these stupid mistakes? (pylint doesn't warn
> me on that)

Can't help you with that.

Have you tried pychecker? I can't help you with that either :)



-- 
Steven



More information about the Python-list mailing list