3 ms·
This uses sys._getframe()[0], a private function which appears to be officially supported by CPython but is not guaranteed to exist in other interpreters. Need
by CivBase 6y ago
This uses sys._getframe()[0], a private function which appears to be officially supported by CPython but is not guaranteed to exist in other interpreters. Needless to say, you probably shouldn't use this in any serious capacity, even if you're using CPython.
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 https://docs.python.org/3/library/sys.html#sys._getframe
- kzrdude 6y agoPython being python, can't you swap out the import machinery and change which compile function is called, alternatively call your own preprocessor before compiling?
- rcxdude 6y agoYup. 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 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#using-hy-from-python 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/ https://pypi.org/project/goto-statement/
- sitkack 6y agohttps://github.com/lihaoyi/macropy https://github.com/lihaoyi/macropy
- tom_mellior 6y agoWith 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.
- fezzez 6y ago^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.