how to use bool
tinnews at isbd.co.uk
tinnews at isbd.co.uk
Thu Jan 3 11:09:53 EST 2008
jimgardener 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 ?
>
With my philosophical programming hat on the first thing I'd say (as a
fairly beginning python programmer) is "avoid multiple returns from a
function/method if at all possible". They breed all sorts of problems
and errors, in particular if there's any clearing up to do you have to
do it in lots of places (or you forget it in some places).
So:-
def mymethod(self):
msg="sthing failed"
success=validateSthing()
if success:
dosomeprocessing()
.....
success=validateSthingelse()
if success:
domoreprocessing()
....
msg="all validation OK"
return (success,msg)
I've lost the different messages for different errors but you get the
idea.
"if success:" rather than "if (success==True)", more readable. For
the opposite "if not success:".
--
Chris Green
More information about the Python-list
mailing list