Can you obtain names from parent scope?

Justin Shaw 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
>

Will,
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.

Good luck
Justin

----------------- Solution ---------------------

import inspect
import linecache
import sre
regx = sre.compile('dbgprint\((\w*)\)')

def dbgprint(var):
    '''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.
    linecache.clearcache()
    f = inspect.currentframe(1)
    file = inspect.getfile(f)
    lnum = f.f_lineno
    line = lc.getline(file, lnum)
    match = regx.search(line)
    if match:
        print '%s = %s' % (match.group(1), var)
    else:
        # bail and just print var
        print var

a = 5
dbgprint(a)







More information about the Python-list mailing list