Re:Python goto implemented with system trace function (2017)
by kzrdude on Tuesday May 05, 2020 @11:29AM
(#23081072)
Python being python, can't you swap out the import machinery and change which compile function is called, alternatively call your own preprocessor before compiling?
Re:Python goto implemented with system trace function (2017)
by rcxdude on Tuesday May 05, 2020 @12:40PM
(#23081925)
Yup. You can basically write your own language with different syntax and get python to treat it like any other python code. Hy is a language which works this way: https://github.com/hylang/hy (see this part of their documentation for how the user can use this: https://docs.hylang.org/en/master/language/interop.html#usin...)
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/
Re:Python goto implemented with system trace function (2017)
by tom_mellior on Tuesday May 05, 2020 @02:52PM
(#23083421)
With a decorator you can parse and rewrite the function's bytecode. If it helps, I'm fairly sure you could also ask for the function's abstract syntax tree, rewrite that, and ask for it to be compiled. So you could build something, but every function using such gotos would have to be decorated with @gotos or whatever.
Re:Python goto implemented with system trace function (2017)
by fezzez on Tuesday May 05, 2020 @07:21PM
(#23086253)
^To add to that. I'm doing exactly that to build this tool that lets you add logging statements onto running python without any restarts.
CPython gives you all the necessary utilities to let you freely manipulate pretty much any function's bytecode.
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