how to use bool

Paul Hankin paul.hankin at gmail.com
Sun Jan 6 14:15:49 CET 2008


On Jan 3, 3:49 pm, jimgarde... at gmail.com wrote:
> hi, i have some code where i set a bool type variable and if the value
> is false i would like to return from the method with an error msg..
> being a beginner I wd like some help here
>
> class myclass:
>      .........
>     def  mymethod(self):
>              success=True
>              msg="all validation OK"
>              success=validateSthing()
>              if(success==False):
>                    msg="sthing failed"
>                    return (success,msg)
>
>              dosomeprocessing()
>              .....
>              success=validateSthingelse()
>              if(success==False):
>                    msg="sthingelse  failed"
>                    return (success,msg)
>              domoreprocessing()
>               ....
>                return(success,msg)
>
> i would like to know if this way of doing this is OK..I have need of
> many kinds of validations in this ..is there a better way of doing
> this ?

As everyone's pointed out, you should use exceptions for this sort of
thing.
>     def  mymethod(self):
>              success=True
>              msg="all validation OK"
>              success=validateSthing()
>              if(success==False):
>                    msg="sthing failed"
>                    return (success,msg)
>
>              dosomeprocessing()
>              .....
>              success=validateSthingelse()
>              if(success==False):
>                    msg="sthingelse  failed"
>                    return (success,msg)
>              domoreprocessing()
>               ....
>                return(success,msg)

As everyone else has pointed out, you should use exceptions for this
sort of thing. But even without exceptions, you can write your code a
lot more cleanly by omitting all the temporary variables. That way,
you don't have to search around to see where things are used (eg.
seeing where "all validation OK" is used requires you to read every
line of your method).

def mymethod(self):
    if not validateSthing():
        return (False, "sthing failed")
    dosomeprocessing()
    ....
    if not validateSthingelse():
        return (False, "sthingelse failed")
    domoreprocessing()
     ...
    return (True, "all validation OK")

Isn't that a lot more readable?

--
Paul Hankin



More information about the Python-list mailing list