If you understood correctly that you want to get an abbreviated name for printing the variable name and its value in the current area? This is generally not possible without using the trace trace function or sys._getframe , which in general should only be used if you know what you are doing. The reason for this is because the print function has no other way to get locales from the call area:
def a(): x = 1 magic_print("x")
What you can do without them explicitly passes this function to local users:
def printNameAndValue(varname, values): print("%s=%s" % (varname, values[varname])) def a(): x = 1 printNameAndValue("x", locals())
EDIT:
See catchemifyoutry answer for a solution using a validation module (which internally uses sys._getframe). For completeness, a solution that uses the trace function directly is useful if you are using python 2.0 and the check is not available;)
from sys import settrace __v = {} #global dictionary that holds the variables def __trace(frame, event, arg): """ a trace function saving the locals on every function call """ global __v if not event == "call": return __trace __v.update(frame.f_back.f_locals) def enableTrace(f): """ a wrapper decorator setting and removing the trace """ def _f(*a, **kwa): settrace(__trace) try: f(*a, **kwa) finally: settrace(None) return _f def printv(vname): """ the function doing the printing """ global __v print "%s=%s" % (vname, __v[vname])
Save it in the module and use it like this:
from modulenamehere import enableTrace, printv @enableTrace def somefunction(): x = 1 [...] printv("x")
l4mpi source share