python goto with system trace function
import sys | |
def j(lineno): | |
frame = sys._getframe().f_back | |
called_from = frame | |
def hook(frame, event, arg): | |
if event == 'line' and frame == called_from: | |
try: | |
frame.f_lineno = lineno | |
except ValueError as e: | |
print "jump failed:", e | |
while frame: | |
frame.f_trace = None | |
frame = frame.f_back | |
return None | |
return hook | |
while frame: | |
frame.f_trace = hook | |
frame = frame.f_back | |
sys.settrace(hook) | |
def foo(): | |
a = 1 | |
j(30) | |
a = 2 | |
print 1 | |
print 2 | |
if a == 1: | |
j(28) | |
print 4 | |
foo() |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
I love to hate this so much. Thank you. |
This comment has been minimized.
This comment has been minimized.
Hehe, should consider renaming "j" to "goto" for full effect. |
This comment has been minimized.
This comment has been minimized.
Great :) Going to study this. Thank you. |
This comment has been minimized.
This comment has been minimized.
I added labels lol import ast
import sys
def label(name):
pass
def j(lineno):
frame = sys._getframe().f_back
called_from = frame
if isinstance(lineno, str):
with open(called_from.f_code.co_filename) as f:
for node in ast.walk(ast.parse(f.read())):
if isinstance(node, ast.Call) \
and isinstance(node.func, ast.Name) \
and node.func.id == 'label' \
and lineno == ast.literal_eval(node.args[0]):
lineno = node.lineno
def hook(frame, event, arg):
if event == 'line' and frame == called_from:
try:
frame.f_lineno = lineno
except ValueError as e:
print "jump failed:", e
while frame:
frame.f_trace = None
frame = frame.f_back
return None
return hook
while frame:
frame.f_trace = hook
frame = frame.f_back
sys.settrace(hook)
def foo():
a = 1
j('l1')
label('l2')
a = 2
print 1
label('l1')
print 2
if a == 1:
j('l2')
print 4
foo() |
This comment has been minimized.
This comment has been minimized.
could someone explain what the hook function is for and who calls it? |
This comment has been minimized.
This comment has been minimized.
Meh... "goto" is already taken on PyPI... :( |
This comment has been minimized.
This comment has been minimized.
The "goto" on pypi follows the same idea, and was made for an April first a couple years ago. It is actually "production quality" and implements labels and a |
This comment has been minimized.
This comment has been minimized.
Can this at GOSUB too ? |
This comment has been minimized.
This comment has been minimized.
How about making a BASIC interpreter, and then a transpiler to convert Python code into BASIC? |
This comment has been minimized.
This comment has been minimized.
I made a py3 port. This one uses relative line numbers though. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
If code were painting, then software engineering is portraiture and this is Dalí.