Is there a label/goto in Python? Is there a label/goto in Python? python python

Is there a label/goto in Python?


No, Python does not support labels and goto, if that is what you're after. It's a (highly) structured programming language.


Python offers you the ability to do some of the things you could do with a goto using first class functions. For example:

void somefunc(int a){    if (a == 1)        goto label1;    if (a == 2)        goto label2;    label1:        ...    label2:        ...}

Could be done in python like this:

def func1():    ...def func2():    ...funcmap = {1 : func1, 2 : func2}def somefunc(a):    funcmap[a]()  #Ugly!  But it works.

Granted, that isn't the best way to substitute for goto. But without knowing exactly what you're trying to do with the goto, it's hard to give specific advice.

@ascobol:

Your best bet is to either enclose it in a function or use an exception. For the function:

def loopfunc():    while 1:        while 1:            if condition:                return

For the exception:

try:    while 1:        while 1:            raise BreakoutException #Not a real exception, invent your ownexcept BreakoutException:    pass

Using exceptions to do stuff like this may feel a bit awkward if you come from another programming language. But I would argue that if you dislike using exceptions, Python isn't the language for you. :-)


I recently wrote a function decorator that enables goto in Python, just like that:

from goto import with_goto@with_gotodef range(start, stop):    i = start    result = []    label .begin    if i == stop:        goto .end    result.append(i)    i += 1    goto .begin    label .end    return result

I'm not sure why one would like to do something like that though. That said, I'm not too serious about it. But I'd like to point out that this kind of meta programming is actual possible in Python, at least in CPython and PyPy, and not only by misusing the debugger API as that other guy did. You have to mess with the bytecode though.