Good python equivalent to C goto

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kurien Mathew

    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;
    }



    Thanks
    Kurien
  • Thomas Mlynarczyk

    #2
    Re: Good python equivalent to C goto

    Kurien Mathew schrieb:
    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;
    }
    while loopCondition:
    if not( cond1 or cond2 or cond3 ):
    stmt1
    stmt2
    stmt3
    stmt4

    Not tested.
    Greetings,
    Thomas

    --
    Ce n'est pas parce qu'ils sont nombreux à avoir tort qu'ils ont raison!
    (Coluche)

    Comment

    • Fredrik Lundh

      #3
      Re: Good python equivalent to C goto

      Kurien Mathew wrote:
      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;
      }
      seems as if you *don't* want to execute the first part if any of the
      conditions are true. in other words,

      while loopCondition:
      if not (condition1 or condition2 or condition3):
      stmt1
      stmt2
      stmt3
      stmt4

      </F>

      Comment

      • Christian Heimes

        #4
        Re: Good python equivalent to C goto

        Kurien Mathew wrote:
        Hello,
        >
        Any suggestions on a good python equivalent for the following C code:
        >
        There are various ways to write your example in Python. For example

        while loopCondition:
        condition = 1
        while condition:
        if condition1:
        break
        if condition2:
        break
        if condition3:
        break
        stmt1
        stmt2
        condition = 0
        else:
        stmt3
        stmt4

        The else block of while isn't execute if you break out of while.

        You can emulate multiple gotos with exceptions. In general you shouldn't
        try to mimic C in Python code. C like Python code is often hard to read
        and slower than well designed Python code.

        Comment

        • Michael Torrie

          #5
          Re: Good python equivalent to C goto

          Dennis Lee Bieber wrote:
          Nasty code even for C... I've never used goto in C... Options:
          convert the statements of next into a function, and put in an else
          clause...
          I think the parent post's pseudocode example was too simple to show the
          real benefits and use cases of goto in C. Obviously his simple example
          was contrived and could easily be solved with proper if tests. Your
          idea of using a function is correct for python, though, but not for C

          However, what you say about else clauses gets extremely hairy when you
          have to deal with multiple nested if statements. The most common use
          case in C for goto is when you have cleanup code that must run before
          leaving a function. Since any number of things could happen while
          processing a function (at any level of the if statement) that would
          trigger an exit, having a whole bunch of else statements gets very, very
          tedious and messy. Often involves a lot of code duplication too. Goto
          is direct and much cleaner and more readable.

          A function in C wouldn't work for this because of scoping rules.

          However it's not necessary in python to do any of this, since you can
          define nested functions that have access to the parent scope. Anytime
          you need to clean up, just call the nested cleanup function and then return.

          Comment

          • Michael Torrie

            #6
            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;
            }
            I think the most direct translation would be this:

            def whateverfunc():

            def next_func():
            stmt3
            stmt4

            while loopCondition:
            if condition1:
            next_func()
            return
            if condition2:
            next_func()
            return
            if condition3:
            next_func()
            return
            stmt1
            stmt2




            Comment

            • Michael Torrie

              #7
              Re: Good python equivalent to C goto

              Michael Torrie wrote:
              I think the most direct translation would be this:
              Nevermind I forgot about the while loop and continuing on after it.
              Guess the function doesn't quite fit this use case after all.

              Comment

              • Carl Banks

                #8
                Re: Good python equivalent to C goto

                On Aug 17, 12:35 am, Michael Torrie <torr...@gmail. comwrote:
                However it's not necessary in python to do any of this, since you can
                define nested functions that have access to the parent scope.  Anytime
                you need to clean up, just call the nested cleanup function and then return.
                That is unnecessary and dangerous in Python.

                98% of the time the Python interpreter cleans up what you would have
                had to clean up by hand in C.

                The rest of the time you should be using a try...finally block to
                guarantee cleanup, or a with block to get the interpreter do it for
                you.

                Calling a nested function to perform cleanup is prone to omission
                errors, and it doesn't guarantee that cleanup will happen if an
                exception is raised.


                Carl Banks

                Comment

                • info@orlans-amo.be

                  #9
                  Re: Good python equivalent to C goto

                  as an oldtimer, I know that in complex code the goto statement is
                  still the easiest to code and understand.

                  I propose this solution using exception.

                  The string exception is deprecated but is simpler for this example.



                  # DeprecationWarn ing: raising a string exception is deprecated

                  def Goto_is_not_dea d(nIn):
                  try:
                  if (nIn == 1): raise 'Goto_Exit'
                  if (nIn == 2): raise 'Goto_Exit'

                  print 'Good Input ' + str(nIn)
                  raise 'Goto_Exit'

                  except 'Goto_Exit':
                  print 'any input ' + str(nIn)

                  if __name__ == '__main__':
                  Goto_is_not_dea d(2)
                  Goto_is_not_dea d(3)

                  Comment

                  • Marc 'BlackJack' Rintsch

                    #10
                    Re: Good python equivalent to C goto

                    On Sat, 16 Aug 2008 23:20:52 +0200, Kurien Mathew wrote:
                    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;
                    }
                    (Don't) use the `goto` module: http://entrian.com/goto/ :-)

                    from goto import goto, label

                    # ...

                    while loop_condition:
                    if condition1 or condition2 or condition3:
                    goto .next
                    print 'stmt1'
                    print 'stmt2'
                    label .next
                    print 'stmt3'
                    print 'stmt4'


                    Ciao,
                    Marc 'BlackJack' Rintsch

                    Comment

                    • Grant Edwards

                      #11
                      Re: Good python equivalent to C goto

                      On 2008-08-16, Dennis Lee Bieber <wlfraed@ix.net com.comwrote:
                      On Sat, 16 Aug 2008 23:20:52 +0200, Kurien Mathew <kmathew@envivi o.fr>
                      declaimed the following in comp.lang.pytho n:
                      >
                      >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;
                      > }
                      >>
                      >
                      Nasty code even for C... I've never used goto in C...
                      I do sometimes, but it's for exception handling, and in Python
                      one uses try/raise/except. The example above isn't the best
                      way to show this, but perhaps something like the code below

                      while loopCondition:
                      try:
                      if condition 1:
                      raise MyException
                      if condition 2:
                      raise MyException
                      if condition 3:
                      raise MyException
                      stmt1;
                      stmt2;
                      stmt3;
                      except: MyException
                      pass
                      stmt4;
                      stmt5;



                      --
                      Grant Edwards grante Yow! People humiliating
                      at a salami!
                      visi.com

                      Comment

                      • Matthew Fitzgibbons

                        #12
                        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;
                        }
                        >
                        >
                        >
                        Thanks
                        Kurien
                        --

                        >
                        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

                        Comment

                        • info@orlans-amo.be

                          #13
                          Re: Good python equivalent to C goto

                          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;
                           }
                          >>
                          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)

                          Comment

                          • Matthew Fitzgibbons

                            #14
                            Re: Good python equivalent to C goto

                            info@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)
                            --

                            >
                            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

                            Comment

                            • Paul Hankin

                              #15
                              Re: Good python equivalent to C goto

                              On Aug 16, 11:20 pm, Kurien Mathew <kmat...@envivi o.frwrote:
                              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;
                                }
                              Extract complex test as a function. Assuming conditions 1, 2 and 3 are
                              difficult enough not to put them all one one line, put them in a
                              function which describes what they're testing.

                              def should_do_12(ar gs):
                              if condition1:
                              return False
                              if condition2:
                              return False
                              if condition3:
                              return False
                              return True

                              while loop_condition:
                              if should_do_12(ar gs):
                              stmt1
                              stmt2
                              stmt3
                              stmt4

                              This is probably the right way to write it in C too.

                              --
                              Paul Hankin

                              Comment

                              Working...