how to use bool

Discussion in 'Python' started by jimgardener@gmail.com, Jan 3, 2008.

  1. Guest

    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
    , Jan 3, 2008
    #1
    1. Advertising

  2. 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 ?


    to test boolean values, it's usually better to use plain "if" or "if
    not" statements:

    if success:
    ... handle success here ...

    if not success:
    ... handle failure here ...

    to report failures, use exceptions (the raise and try/except
    statements). see the tutorial for more on this topic.

    </F>
    Fredrik Lundh, Jan 3, 2008
    #2
    1. Advertising

  3. Guest

    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
    , Jan 3, 2008
    #3
  4. Chris Mellon Guest

    On 03 Jan 2008 16:09:53 GMT, <> wrote:
    >
    > 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).
    >


    This advice is highly controversial, and in the presence of exceptions
    it is, at best, voodoo coding. Since your function can exit at any
    point whether you do it intentionally or not, if you have crucial
    cleanup it's best to write your code in a way that does it correctly
    even if you return early. Following this style also often leads to odd
    contortions, like extra layers of indentation, and a proliferation of
    temporary flags and value-holders that aren't necessary if you write
    the code in a more straight forward manner.

    Make your decisions on a case by case basis of complexity,
    readability, and reliability instead of following pronouncements from
    on high (especially decades old pronouncements made in a different
    context). Forcing a single return site in the code below adds
    complexity, arguable harms readability, and provides *zero* benefit in
    the code at hand.

    > 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
    >
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >
    Chris Mellon, Jan 3, 2008
    #4
  5. Guest

    Chris Mellon <> wrote:
    > On 03 Jan 2008 16:09:53 GMT, <> wrote:
    > >
    > > 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).
    > >

    >
    > This advice is highly controversial, and in the presence of exceptions
    > it is, at best, voodoo coding. Since your function can exit at any
    > point whether you do it intentionally or not, if you have crucial
    > cleanup it's best to write your code in a way that does it correctly
    > even if you return early. Following this style also often leads to odd
    > contortions, like extra layers of indentation, and a proliferation of
    > temporary flags and value-holders that aren't necessary if you write
    > the code in a more straight forward manner.
    >

    OK, I agree, I had my C hat on (no exceptions).

    On the other hand if you end with lots of levels of indentation going
    this way it suggests to me that maybe breaking up into more functions
    would be a good idea.


    > Make your decisions on a case by case basis of complexity,
    > readability, and reliability instead of following pronouncements from
    > on high (especially decades old pronouncements made in a different
    > context). Forcing a single return site in the code below adds
    > complexity, arguable harms readability, and provides *zero* benefit in
    > the code at hand.
    >
    > > 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
    > >
    > > --
    > > http://mail.python.org/mailman/listinfo/python-list
    > >


    --
    Chris Green
    , Jan 4, 2008
    #5
  6. Paul McGuire Guest

    On Jan 3, 10:09 am, wrote:
    >
    > 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).
    >


    This conventional wisdom predates the introduction of constructs such
    as try-catch-finally. In fact, you are just lulling yourself into
    some false security if you think that that single return at the end of
    your method is the only exit point of your routine. Exceptions can
    (and will) happen just about anywhere.

    I know, you had your C hat on, but even C++'ers fall into this trap.
    I was on a project that cited explicit delete statements during code
    reviews as likely memory leaks in the face of exceptions, and each was
    to be replaced with auto-cleanup objects such as auto_ptr. The same
    was done for other resource alloc/release pairs, such as locks,
    database connections, cursors, etc. These were looooong-running
    server processes, and they ran for months with no memory growth at
    all.

    If I were to suggest a similar topic for Python code reviews, it would
    be to look at paired statements and to ensure that the cleanup/
    recovery statement was wrapped in a finally block.

    There's more than just memory that needs bookkeeping, so garbage
    collection wont solve all these other resource management problems.

    -- Paul
    Paul McGuire, Jan 4, 2008
    #6
  7. bukzor Guest

    On Jan 3, 7:49 am, 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


    class SthingError(Exception):
    def __init__(self, success, msg):




    class myclass:
    .........
    def mymethod(self):
    success=True
    if not validateSthing():
    msg="sthing failed"
    return (success,msg)

    dosomeprocessing()
    .....
    if not validateSthingelse():
    msg="sthingelse failed"
    return (success,msg)
    domoreprocessing()
    ....
    return(success,"all validation OK")
    bukzor, Jan 4, 2008
    #7
  8. bukzor Guest

    On Jan 4, 8:51 am, bukzor <> wrote:
    > On Jan 3, 7:49 am, 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()
    bukzor, Jan 4, 2008
    #8
  9. Guest

    hi bukzor & everyone who replied

    thanks for the detailed replies
    will try to write that way
    thanx a lot
    jim



    bukzor wrote:
    > On Jan 4, 8:51 am, bukzor <> wrote:
    >
    > #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()
    , Jan 6, 2008
    #9
  10. Paul Hankin Guest

    On Jan 3, 3:49 pm, 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
    Paul Hankin, Jan 6, 2008
    #10
  11. Guest

    some more doubts in this area,,forgive the ignorance of a beginner

    i have

    class MyError(Exception):
    def __init__(self,msg)
    self.msg=msg

    now my method that can raise this is

    class SomeClass:
    ...........
    def mymethod(self):
    if (somecondition):
    raise MyError("somecondn failed")

    if another method in the same class calls this method but wants to
    pass the error to a gui code which calls it,,can i do like this

    def callingmethode(self):
    try:
    mymethod()
    except MyError,myerr:
    raise myerr

    so that I can handle the error in a gui code that calls
    callingmethode()

    class MyGUI:
    def guimethode(self):
    someinst=SomeClass()
    try:
    someinst.callingmethode()
    except MyError,myer:
    self.dealwithMyError(myer)

    is this kind of raising exception the correct way?I am getting syntax
    error at
    except MyError,myerr:
    raise myerr
    , Jan 6, 2008
    #11
  12. Guest

    forget about syntax err.. sorry ..but still would like to know if
    raising exception inside an except clause the right way?
    , Jan 6, 2008
    #12
  13. wrote:
    > ...if another method in the same class calls this method but wants to
    > pass the error to a gui code which calls it,,can i do like this
    >
    > def callingmethode(self):
    > try:
    > mymethod()
    > except MyError,myerr:
    > raise myerr
    >
    > so that I can handle the error in a gui code that calls
    > callingmethode()
    >
    > class MyGUI:
    > def guimethode(self):
    > someinst=SomeClass()
    > try:
    > someinst.callingmethode()
    > except MyError,myer:
    > self.dealwithMyError(myer)
    >
    > is this kind of raising exception the correct way?I am getting syntax
    > error at
    > except MyError,myerr:
    > raise myerr
    >


    Almost. The callingmethode code above behaves like:
    def callingmethode(self):
    mymethod()
    except that your code hides the traceback information.
    If you need to do something locally (other than passing
    along the exception), use either:
    def callingmethode(self):
    try:
    mymethod()
    finally:
    cleanup_stuff()
    or (if you have some exception-specific code to do):
    def callingmethode(self):
    try:
    mymethod()
    except MyError,myerr:
    stuff_only_for_exceptional_cases()
    raise # Note that this keeps the original traceback.


    --Scott David Daniels
    Scott David Daniels, Jan 6, 2008
    #13
  14. bukzor Guest

    On Jan 6, 8:56 am, wrote:
    > some more doubts in this area,,forgive the ignorance of a beginner
    >
    > i have
    >
    > class MyError(Exception):
    > def __init__(self,msg)
    > self.msg=msg
    >
    > now my method that can raise this is
    >
    > class SomeClass:
    > ...........
    > def mymethod(self):
    > if (somecondition):
    > raise MyError("somecondn failed")
    >
    > if another method in the same class calls this method but wants to
    > pass the error to a gui code which calls it,,can i do like this
    >
    > def callingmethode(self):
    > try:
    > mymethod()
    > except MyError,myerr:
    > raise myerr
    >
    > so that I can handle the error in a gui code that calls
    > callingmethode()
    >
    > class MyGUI:
    > def guimethode(self):
    > someinst=SomeClass()
    > try:
    > someinst.callingmethode()
    > except MyError,myer:
    > self.dealwithMyError(myer)
    >
    > is this kind of raising exception the correct way?I am getting syntax
    > error at
    > except MyError,myerr:
    > raise myerr


    It's unnecessary to catch the exception and raise it again. The
    default action for an uncaught exception it to raise it higher.

    Also this class doesn't make much sense:

    > class MyError(Exception):
    > def __init__(self,msg)
    > self.msg=msg



    This doesn't call the super class's init function. You'd want to do
    something like this:

    > class MyError(Exception):
    > def __init__(self,msg)
    > self.msg=msg
    > Exception.___init__(self)


    Also, the first argument to the Exception constructor is a text
    message, so you could just do this:

    > class MyError(Exception):
    > def __init__(self,msg)
    > Exception.___init__(self, msg)


    This is exactly the default constructor, so you could write it this
    way:

    > class MyError(Exception):
    > pass


    or as a one-liner:

    > class MyError(Exception): pass


    When you want to access the message out of the exception, you can use
    'e.message' or 'str(e)'. If you want to print the exception's message,
    just do 'print e'. Besides that, your code looks good. Might want to
    read the exceptions chapter of the documentation: http://docs.python.org/tut/node10.html

    --Bukzor
    bukzor, Jan 6, 2008
    #14
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Weng Tianxiang
    Replies:
    2
    Views:
    459
    Weng Tianxiang
    Jun 21, 2005
  2. Ignacio Machin

    Re: Convert DataRow content to bool

    Ignacio Machin, Jul 7, 2003, in forum: ASP .Net
    Replies:
    0
    Views:
    365
    Ignacio Machin
    Jul 7, 2003
  3. Eliyahu Goldin

    Re: Convert DataRow content to bool

    Eliyahu Goldin, Jul 7, 2003, in forum: ASP .Net
    Replies:
    0
    Views:
    351
    Eliyahu Goldin
    Jul 7, 2003
  4. Georg Mayer
    Replies:
    1
    Views:
    321
    cosine... zero
    Jun 23, 2004
  5. Replies:
    1
    Views:
    302
Loading...

Share This Page