I'm trying to replace my Template(s).substitute("$a,$b", locals())
with something short like
sub("$a,$b")
However, I don't have access to locals of surrounding scope inside sub()
, any idea how to get them?
One possible workaround I found is to throw an exception, catch it, and step along the frames to find the previous frame, but perhaps there's an easier way?
import traceback, sys, code
try:
2/0
except Exception as e:
type, value, tb = sys.exc_info()
traceback.print_exc()
last_frame = lambda tb=tb: last_frame(tb.tb_next) if tb.tb_next else tb
frame = last_frame().tb_frame
ns = dict(frame.f_globals)