Python goto implemented with system trace function (2017)
gist.github.com
gist.github.com
That said... I wonder what it would take to add support for labels. Jumping back to a previous location would be trivial; just create a sister function to associate the line with some unique string. But is there any way to register a label for a line that hasn't been executed?
I know CPython normally precompiles modules instead of literally interpreting them line-by-line, but I've never seen any code that interfaces with the precompiler itself. Does CPython support anything like preprocessor commands that might make it possible to support future labels?
You could easily wrap the interpreter with a custom preprocessor, but that's boring.
[0] https://docs.python.org/3/library/sys.html#sys._getframe
I think goto has been implemented in a few different ways in python. Here's another example which abuses existing syntax and edits the bytecode of the function after its compiled: https://pypi.org/project/goto-statement/
CPython gives you all the necessary utilities to let you freely manipulate pretty much any function's bytecode.
from goto import comefromThis Gist is still super cool, though.
QBasic let you use either a line number or a label, I believe they only kept line numbers after labels were introduced for backwards compatibility.
I know I'm veering way off topic but for as much disdain as BASICs receive, I really do feel like coding up a simple game was much easier for teenage-me in QBasic than it was in Python with pygame, for whatever reason.
I wasted a lot of time with C/C++, if I had immersed myself in QBasic, I would have better actualized myself.
LABEL = sys._getframe().f_lineno
print(1)
j(LABEL) print(1)
goto('MYLABEL')
print(2)
label('MYLABEL')
print(3)
Or better yet... for x in range(10):
for y in range(10):
if x == 5 and y == 5:
print(x, y)
goto('MULTIBREAK')
label('MULTIBREAK')How to do this: create your ExceptionGoTo class which will be handled on high level function and add callback as exception parameter, in catch you can call it.
I'm not saying that it will be exactly goto to certain line, but logically it will behave as you suppose to use goto.