Good python equivalent to C goto

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • info@orlans-amo.be

    #16
    Re: Good python equivalent to C goto

    On Aug 17, 9:23 pm, Matthew Fitzgibbons <eles...@nienna .orgwrote:
    i...@orlans-amo.be wrote:
    On Aug 17, 8:09 pm, Matthew Fitzgibbons <eles...@nienna .orgwrote:
    Kurien Mathew wrote:
    >Hello,
    >Any suggestions on a good python equivalent for the following C code:
    >while (loopCondition)
    >{
    >    if (condition1)
    >        goto next;
    >    if (condition2)
    >        goto next;
    >    if (condition3)
    >        goto next;
    >    stmt1;
    >    stmt2;
    >next:
    >    stmt3;
    >    stmt4;
    > }
    >Thanks
    >Kurien
    >--
    >>http://mail.python.org/mailman/listinfo/python-list
    I would not be too happy if I saw C code like that in my repository.
    This is equivalent:
    >
    while (loopCondition) {
         if (!(condition1 || condition2 || condition3)) {
             stmt1;
             stmt2;
         }
         stmt3;
         stmt4;
    >
    }
    >
    In Python:
    >
    while (loopCondition) :
         if not (condition1 or condition2 or condition3):
             stmt1
             stmt2
         stmt3
         stmt4
    >
    If stmt3 and stmt4 are error cleanup code, I would use try/finally.
    >
    while loopCondition:
         try:
             if condition1:
                 raise Error1()
             if condition2:
                 raise Error2()
             if condition3:
                 raise Error3()
             stmt1
             stmt2
         finally:
             stmt3
             stmt4
    >
    This will also bail out of the loop on and exception and the exception
    will get to the next level. If you don't want that to happen, put an
    appropriate except block before the finally.
    >
    -Matt- Hide quoted text -
    >
    - Show quoted text -
    >
    class Goto_Target(Exc eption):
        pass
    >
    def Goto_is_not_dea d(nIn):
        try:
            if (nIn == 1): raise Goto_Target
            if (nIn == 2): raise Goto_Target
    >
            inv = 1.0 / nIn
            print 'Good Input ' + str(nIn) + ' inv=' + str(inv)
    >
        except Goto_Target:
            pass
        except Exception, e:
            print 'Error Input ' + str(nIn) + ' ' + str(e)
        finally:
            print 'any input ' + str(nIn)
    >
    if __name__ == '__main__':
        Goto_is_not_dea d(0)
        Goto_is_not_dea d(2)
        Goto_is_not_dea d(3)
    --
    http://mail.python.org/mailman/listinfo/python-list
    >
    I think this is needlessly ugly. You can accomplish the same with a
    simple if-else. In this case you're also masking exceptions other than
    Goto_Target, which makes debugging _really_ difficult. If you need to
    have the cleanup code executed on _any_ exception, you can still use
    try-finally without any except blocks. Your code is equivalent to this:
    >
    def goto_is_dead(n) :
         try:
             if n == 0 or n == 1 or n == 2:
                 # if you're validating input, validate the input
                 print "Error Input %s" % n
             else:
                 print "Good Input %s inv= %s" % (n, (1. / n))
         finally:
             print "any input %s" % n
    >
    if __name__ == '__main__':
         goto_id_dead(0)
         goto_id_dead(2)
         goto_id_dead(3)
    >
    More concise, readable, and maintainable.
    >
    -Matt- Hide quoted text -
    >
    - Show quoted text -
    as mentioned 'in complex code the goto statement is still the easiest
    to code and understand'.
    The examples are very small and do not require that at all. I agree
    it's ugly.
    Just to show a way to do it.

    A very few functions where I use goto in C or C# are a few hundred
    lines of code, difficult to split in smaller functions.
    A lot of common data.
    One coming to my mind is a complex validation function for the user
    input of a complex transaction.
    If any test fails, goto the cleaning part and issue error message.

    The goto code is the simpler way to do it.
    We are not talking about simple if-else, but let say 20 if-else.
    Many nested if-else are more difficult to understand and do not fit
    better the semantics.

    Comment

    • Fredrik Lundh

      #17
      Re: Good python equivalent to C goto

      info@orlans-amo.be wrote:
      The goto code is the simpler way to do it.
      We are not talking about simple if-else, but let say 20 if-else.
      Many nested if-else are more difficult to understand and do not fit
      better the semantics.
      let's see...

      $ cd ~/svn/python25
      $ grep goto */*.c | wc
      2107 7038 86791

      but given that the Python language doesn't have a goto statement, can we
      perhaps drop this subtopic now?

      </F>

      Comment

      • Matthew Fitzgibbons

        #18
        Re: Good python equivalent to C goto

        as mentioned 'in complex code the goto statement is still the easiest
        to code and understand'.
        The examples are very small and do not require that at all. I agree
        it's ugly.
        Just to show a way to do it.
        >
        A very few functions where I use goto in C or C# are a few hundred
        lines of code, difficult to split in smaller functions.
        A lot of common data.
        One coming to my mind is a complex validation function for the user
        input of a complex transaction.
        If any test fails, goto the cleaning part and issue error message.
        >
        The goto code is the simpler way to do it.
        We are not talking about simple if-else, but let say 20 if-else.
        Many nested if-else are more difficult to understand and do not fit
        better the semantics.
        --

        >
        I'm sorry, but if you have any single function that's a few hundred
        lines of code, you need to do some serious refactoring. How do you even
        begin to test that? A goto is just a hack that hides underlying
        problems. If I see a function of more than about twenty lines or having
        more than two or three execution paths, I start thinking of ways to
        break it down.

        There are a lot of approaches. Paul Hankin put all the conditionals in a
        helper function. Similarly, you could do something like this (for more
        fun make the validators pluggable):

        # each validator is a function that takes the input the be validated
        # and returns True for good input; otherwise False
        _foo_validators = [_check_this, _check_that, _check_the_othe r] # etc.

        def foo(input):
        for v in _validators:
        if not v(input):
        _on_bad_input(i nput)
        break
        else:
        _on_good_input( input)
        _on_all_input(i nput)

        Alternatively, you can often turn complex input validation into a state
        machine.

        -Matt

        Comment

        • Chuck Rhode

          #19
          Re: Good python equivalent to C goto

          On Sun, 17 Aug 2008 09:08:35 -0500, Grant Edwards wrote:
          In Python one uses try/raise/except.
          At the risk of introducing an anachronism and in deference to
          Mr. "ElementTre e" Lundh, I now invoke Godwin's Law (1990):

          Isn't *try/except* kinda sorta like the musty, old *come from*
          construct proposed for *fortran*?

          Here there be typos (abject apologies):

          o Clark, R. Lawrence. "A Linguistic Contribution to GOTO-less
          Programming." _Datamation_ Dec. 1973. 18 Aug. 2008
          <http://www.fortranlib. com/gotoless.htm>.

          --
          ... Be Seeing You,
          ... Chuck Rhode, Sheboygan, WI, USA
          ... Weather: http://LacusVeris.com/WX
          ... 71° — Wind W 9 mph

          Comment

          • Robin Becker

            #20
            Re: Good python equivalent to C goto

            Kurien Mathew wrote:
            Hello,
            >
            Any suggestions on a good python equivalent for the following C code:
            >
            while (loopCondition)
            {
            if (condition1)
            goto next;
            if (condition2)
            goto next;
            if (condition3)
            goto next;
            stmt1;
            stmt2;
            next:
            stmt3;
            stmt4;
            }
            >
            such a pity that the goto module



            never got into core python :)
            --
            Robin Becker

            Comment

            • Reedick, Andrew

              #21
              RE: Good python equivalent to C goto


              -----Original Message-----
              From: python-list-bounces+jr9445= att.com@python. org [mailto:python-
              list-bounces+jr9445= att.com@python. org] On Behalf Of Kurien Mathew
              Sent: Saturday, August 16, 2008 5:21 PM
              To: python-list@python.org
              Subject: Good python equivalent to C goto

              Hello,

              Any suggestions on a good python equivalent for the following C code:

              while (loopCondition)
              {
              if (condition1)
              goto next;
              if (condition2)
              goto next;
              if (condition3)
              goto next;
              stmt1;
              stmt2;
              next:
              stmt3;
              stmt4;
              }

              =============== ============
              Use a flag and a one loop for loop


              while loopCondition:
              flag = False
              for i in range(1):
              if condition1:
              break
              if condition2:
              break
              if condition3:
              break
              stmt1
              stmt2
              flag = True
              if not flag:
              stmt3
              stmt4


              =============== ============
              Or just a straight flag

              while ( loopCondition ):
              flag = False

              if (condition1)
              flag = True # goto next;
              if (not flag and condition2)
              flag = True # goto next;
              if (not flag and condition3)
              flag = True # goto next;

              if not flag:
              stmt1
              stmt2
              else
              stmt3
              stmt4



              *****

              The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA622


              Comment

              • Paul McGuire

                #22
                Re: Good python equivalent to C goto

                On Aug 17, 1:09 pm, Matthew Fitzgibbons <eles...@nienna .orgwrote:
                Kurien Mathew wrote:
                Hello,
                >
                Any suggestions on a good python equivalent for the following C code:
                >
                while (loopCondition)
                {
                    if (condition1)
                        goto next;
                    if (condition2)
                        goto next;
                    if (condition3)
                        goto next;
                    stmt1;
                    stmt2;
                next:
                    stmt3;
                    stmt4;
                 }
                >>
                I would not be too happy if I saw C code like that in my repository.
                This is equivalent:
                >
                while (loopCondition) {
                     if (!(condition1 || condition2 || condition3)) {
                         stmt1;
                         stmt2;
                     }
                     stmt3;
                     stmt4;
                >
                }
                >
                In Python:
                >
                while (loopCondition) :
                     if not (condition1 or condition2 or condition3):
                         stmt1
                         stmt2
                     stmt3
                     stmt4
                >
                If stmt3 and stmt4 are error cleanup code, I would use try/finally.
                >
                while loopCondition:
                     try:
                         if condition1:
                             raise Error1()
                         if condition2:
                             raise Error2()
                         if condition3:
                             raise Error3()
                         stmt1
                         stmt2
                     finally:
                         stmt3
                         stmt4
                >
                This will also bail out of the loop on and exception and the exception
                will get to the next level. If you don't want that to happen, put an
                appropriate except block before the finally.
                >
                -Matt- Hide quoted text -
                >
                - Show quoted text -
                Close, but there is no reason for the conditions to raise anything,
                they can just use the continue statement:

                i = 20
                while i 0:
                try:
                if i % 2:
                continue
                if i % 3:
                continue
                print i, "is even and a multiple of 3"
                finally:
                i -= 1

                Prints:
                18 is even and a multiple of 3
                12 is even and a multiple of 3
                6 is even and a multiple of 3

                I think this is closest to the OP's stated requirements.

                -- Paul

                Comment

                • Matthew Fitzgibbons

                  #23
                  Re: Good python equivalent to C goto

                  Paul McGuire wrote:
                  On Aug 17, 1:09 pm, Matthew Fitzgibbons <eles...@nienna .orgwrote:
                  >Kurien Mathew wrote:
                  >>Hello,
                  >>Any suggestions on a good python equivalent for the following C code:
                  >>while (loopCondition)
                  >>{
                  >> if (condition1)
                  >> goto next;
                  >> if (condition2)
                  >> goto next;
                  >> if (condition3)
                  >> goto next;
                  >> stmt1;
                  >> stmt2;
                  >>next:
                  >> stmt3;
                  >> stmt4;
                  >> }
                  >>Thanks
                  >>Kurien
                  >>--
                  >>http://mail.python.org/mailman/listinfo/python-list
                  >I would not be too happy if I saw C code like that in my repository.
                  >This is equivalent:
                  >>
                  >while (loopCondition) {
                  > if (!(condition1 || condition2 || condition3)) {
                  > stmt1;
                  > stmt2;
                  > }
                  > stmt3;
                  > stmt4;
                  >>
                  >}
                  >>
                  >In Python:
                  >>
                  >while (loopCondition) :
                  > if not (condition1 or condition2 or condition3):
                  > stmt1
                  > stmt2
                  > stmt3
                  > stmt4
                  >>
                  >If stmt3 and stmt4 are error cleanup code, I would use try/finally.
                  >>
                  >while loopCondition:
                  > try:
                  > if condition1:
                  > raise Error1()
                  > if condition2:
                  > raise Error2()
                  > if condition3:
                  > raise Error3()
                  > stmt1
                  > stmt2
                  > finally:
                  > stmt3
                  > stmt4
                  >>
                  >This will also bail out of the loop on and exception and the exception
                  >will get to the next level. If you don't want that to happen, put an
                  >appropriate except block before the finally.
                  >>
                  >-Matt- Hide quoted text -
                  >>
                  >- Show quoted text -
                  >
                  Close, but there is no reason for the conditions to raise anything,
                  they can just use the continue statement:
                  >
                  i = 20
                  while i 0:
                  try:
                  if i % 2:
                  continue
                  if i % 3:
                  continue
                  print i, "is even and a multiple of 3"
                  finally:
                  i -= 1
                  >
                  Prints:
                  18 is even and a multiple of 3
                  12 is even and a multiple of 3
                  6 is even and a multiple of 3
                  >
                  I think this is closest to the OP's stated requirements.
                  >
                  -- Paul
                  --

                  >
                  I'm aware my example where I raised exceptions was functionally
                  different ("This will bail out of the loop on an exception and the
                  exception will get to the next level.") Just thinking in terms of
                  telling the caller something went wrong. The other examples were
                  functionally equivalent, however.

                  Still, this is the best way so far. :) I never thought of using continue
                  with finally. It gets added to my Python tricks file for future use.

                  -Matt

                  Comment

                  Working...