Can you obtain names from parent scope?
wyojustin at hotmail.com
Sun Jan 19 19:18:20 CET 2003
"Will Sadkin" <wsadkin at nameconnector.com> wrote in message
news:850fb3a6.0301170751.488179c6 at posting.google.com...
> I want to write a function that takes an arbitrary set of objects,
> and prints them in the form "name = <value>." That is, I want to be
> able to say:
> >>> a = 'hi!'
> >>> dbgval(a)
> a = hi!
> >>> b = 2
> >>> dbgval(b)
> b = 2
I was curoius about this myself. You post got me to dive in. It looks like
inspect will work with linecache to get the result you want. I grab the
calling line and get the variable name from a regx. Right now it only works
for a single arg but the extension is obvious.
----------------- Solution ---------------------
regx = sre.compile('dbgprint\((\w*)\)')
'''Print the name of var with its value in the callers scope'''
# Clear to be on the safe side. If the code is not being edited you
don't need this.
f = inspect.currentframe(1)
file = inspect.getfile(f)
lnum = f.f_lineno
line = lc.getline(file, lnum)
match = regx.search(line)
print '%s = %s' % (match.group(1), var)
# bail and just print var
a = 5
More information about the Python-list