how to use bool

bukzor workitharder at gmail.com
Fri Jan 4 12:22:29 EST 2008


On Jan 4, 8:51 am, bukzor <workithar... at gmail.com> wrote:
> On Jan 3, 7:49 am, 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 ?
>
> > thank you


Please ignore my previous post. I accidentally submitted early. I made
your example runnable (hope you don't mind). The 'pythonic' way to do
error handling is to use exceptions. Below is a pretty good example.
Also I've elimiated all your temporary variables. Your original
function is quite short now and does the same thing. You can expand
out the derived exception class if you want to pass more data to your
error handler, but generally the message is enough, and that comes
with the default constructor.


#helper functions
from time import time
from random import seed
seed(time())
def random(chance):
    from random import uniform
    if uniform(0, 1) < chance: return True
    else: return False
def dosomeprocessing(x):
    if random(.1): raise Exception("Something bad happened while
processing %s!" % x)
    else: print x
def validateSthing():
    if random(.2): raise SthingError("this Sthing is messed up!")


#rewrite of your example
class SthingError(Exception): pass
class myclass:
    def  mymethod(self):
         validateSthing()
         dosomeprocessing(1)
         validateSthing()
         dosomeprocessing(2)



#exercise of the class and error handling
m = myclass()
try:
    m.mymethod()
    print "Completed successfully!"
except SthingError, ste:
    print "STHINGERROR:"
    print ste
except Exception, e: print e

print
print "This time no error handling:"
m.mymethod()




More information about the Python-list mailing list