"Goto" statement in Python

Ian Kelly ian.g.kelly at gmail.com
Thu Apr 13 20:36:57 EDT 2017


On Thu, Apr 13, 2017 at 4:59 PM, bartc <bc at freeuk.com> wrote:
> On 13/04/2017 22:58, Ian Kelly wrote:
>>
>> On Thu, Apr 13, 2017 at 3:27 PM, Dennis Lee Bieber
>> <wlfraed at ix.netcom.com> wrote:
>>>
>>> On Thu, 13 Apr 2017 15:52:24 +0100, bartc <bc at freeuk.com> declaimed the
>>> following:
>>>
>>>> 'goto' would be one easy-to-execute byte-code; no variables, objects or
>>>> types to worry about. If implemented properly (with the byte-code
>>>> compiler using a dedicated name-space for labels) there would be no name
>>>> lookups.
>>>>
>>>
>>>         Only if GOTO is not allowed to break out of namespaces...
>>>
>>>         NO GOTO from inside a function to some global catch-all
>>> handler...
>
>
> (That doesn't happen. No sane language would allow it, not on the user-side
> anyway.)

Well, you can do it in Assembly. And BASIC, if you count the primitive
GOSUB-type subroutines, though modern BASICs have real subroutines
that don't allow it.

>>>         Once you permit uncontrolled/unlimited GOTO you have to be
>>> concerned
>>> with stack-frames and object life-times.
>>
>>
>> Even within a function you would still have to be concerned about a
>> goto from inside a try or with block to outside of that block, as the
>> finally block or the context manager's __exit__ still need to be
>> executed on the way out.
>
>
> So how does 'break' manage it? I assume break works from inside a try- or
> with-block.

Yes, it would have to work similarly to break, continue and return. I
didn't mean to imply that it was impossible, only that it's not quite
as simple as just modifying a program counter.

For reference, here's what break inside a try block compiles to:

>>> dis.dis("""
... while True:
...     try:
...         break
...     finally:
...         print("Bye")
... """)
  2           0 SETUP_LOOP              22 (to 24)

  3     >>    2 SETUP_FINALLY            6 (to 10)

  4           4 BREAK_LOOP
              6 POP_BLOCK
              8 LOAD_CONST               0 (None)

  6     >>   10 LOAD_NAME                0 (print)
             12 LOAD_CONST               1 ('Bye')
             14 CALL_FUNCTION            1
             16 POP_TOP
             18 END_FINALLY
             20 JUMP_ABSOLUTE            2
             22 POP_BLOCK
        >>   24 LOAD_CONST               0 (None)
             26 RETURN_VALUE


More information about the Python-list mailing list