Along the lines of rewriting bytecode at runtime, <a href="https://www.python.org/dev/peps/pep-0302/" rel="nofollow">https://www.python.org/dev/peps/pep-0302/</a> lets you arbitrarily hook Python's import process and rewrite .pyc files as desired.<p>As a practical application, pytest uses this to take the statement `assert foo == bar` and rewrite the AST into a number of instructions that extract the values of foo and bar and print them if the assertion fails: <a href="http://pybites.blogspot.com/2011/07/behind-scenes-of-pytests-new-assertion.html" rel="nofollow">http://pybites.blogspot.com/2011/07/behind-scenes-of-pytests...</a> (<a href="https://docs.pytest.org/en/6.2.x/assert.html" rel="nofollow">https://docs.pytest.org/en/6.2.x/assert.html</a> for those unfamiliar with the library) - so if you use pytest, you're already relying on these arcane techniques!
There was an equally intriguing Python goto implementation posted last year¹, with some interesting comments²(including some in the gist itself).<p>This version does seem better, but I'm not really sure that is a good thing.<p>¹ <a href="https://gist.github.com/georgexsh/ede5163a294ced53c3e2369ccaa392cc" rel="nofollow">https://gist.github.com/georgexsh/ede5163a294ced53c3e2369cca...</a><p>² <a href="https://news.ycombinator.com/item?id=23076859" rel="nofollow">https://news.ycombinator.com/item?id=23076859</a>
Just... out of curiosity as someone who learned to code in BASIC on a TRS-80... <i>WHY ON EARTH</i> would you ever want goto or gosub statements instead of proper loops and methods? It's not like they're faster. They certainly don't make code more readable. The last time I had to use that type of construct was gotoAndStop() in Flash, which at least had the benefit of queueing up a bunch of art and sound effects. Other than the "neat-o" factor, what's the use case or impetus behind this apparent horror?
Javascript has a rare yet similar feature called label<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...</a>
Exceptions are forward gotos. A "while" loop with continue and break is backward goto.
The only thing missing is break from nested while. Java has one, called break with label, one of more obscure features of language.
So, in a sense, python already does have goto.
Great! It's too bad that python's jump instructions only accept constant targets or constant offests (which seem like they end up being equivalent), otherwise this approach could also support labels-as-values.