python-goto enables you a goto syntax. If you have coded Python long enough, you might ask why would somebody do this? That is because they can.

Nonetheless, I can think of one good use, I have always wanted a similar behavior as in Bash’s continue and break syntax, which allows you to specify how many levels you want to continue from or break out. With this goto, not only you can break or continue, you can jump to anywhere within the nested loops.

Imagine the following code, you can break out at once,


from goto import with_goto

@with_goto
def func():
for i in range(2):
for j in range(2):
for k in range(2):
for m in range(2):
goto .end
label .end
return (i, j, k, m)

print(func())

I am sure we all have coded something once when you need to break out a simple 2-level nested loops. How would you do that? Use an extra variable? Use an function with return as break? Or just try to flat out the loop?

Truth is, even breaking out of nested loops is really helpful, I don’t think I would even consider using this module, I just don’t want an extra dependency, although you can ship with your code without worrying the copyright, it’s public domain. However, I would rather to live with ugly way to break out, but that’s just me. If it’s safe, why not, if you are willing to use.

I honestly don’t reckon goto is a bad concept probably in any programming language, utilize all tools to all potentials, that’s good coding in my opinion, although “good” is quite subjective.

Nevertheless, it’s just like C’s goto, you can’t jump to another function or module, or another loop unless it’s part of same nested loops in direct line, and others as noted in another implementation by Richie Hindle on April 1st, 2004, using a trace function. He also said:

The “goto” module was an April Fool’s joke, published on 1st April 2004. Yes, it works, but it’s a joke nevertheless. Please don’t use it in real code!

python-goto was written by Sebastian Noack on 2015-09-20 in Python 2 and 3 under the Unlicense, and only 98 LOC1.

[1]git-7cc8a5a179c143e179203e7617f4c3f7dc6637a0, 2015-09-22.