Can you obtain names from parent scope?

Justin Shaw wyojustin at
Sun Jan 19 19:18:20 CET 2003

"Will Sadkin" <wsadkin at> wrote in message
news:850fb3a6.0301170751.488179c6 at
> 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.

Good luck

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

a = 5

More information about the Python-list mailing list