boolean from a function

Duncan Booth duncan.booth at invalid.invalid
Tue Dec 13 12:42:51 EST 2011


Andrea Crotti <andrea.crotti.0 at gmail.com> 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
> 
> Now somewhere else I had
> 
> if func_bool:
>      # do something
> 
> 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)
> I don't think I will ever (or almost) have to use a function as a 
> boolean, instead of its return value...

For this particular example why don't you just write 'if x: # do 
something'?

More generally rather than having a global function make it a property on 
an object.

    class Snark:
        def __init__(self, something):
            self.boojum = ...

        @property
        def is_a_bookum(self):
           return self.boojum

    hunted = Snark(whatever)


Then you can write:

    if hunted.is_a_boojum:
        self.vanish_away()

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list