Little Q: how to print a variable's name, not its value?

Aaron Bingham bingham at cenix-bioscience.com
Thu Mar 31 01:49:39 EST 2005


"stewart.midwinter at gmail.com" <stewart.midwinter at gmail.com> writes:

> Restating:  I'm doing some debugging of some code.  I want to print out
> the value of two variables whose names are known.  Let's call them
> myTime and myPlace.
>
> #debug:
> if self.debug:
>    print "myTime = %s, myPlace = %s" % (myTime, myPlace)
>
> Notice that I had to type the variable's name once as an object, and
> once as the string representation of that object, i.e. the object's
> name.
> I wondered whether it might not be possible to do something like this:
> if self.debug:
>    print "%s = %s" % ( name(myTime), myTime )
> where 'name' is the method or trick I'm after.

I must admit this is a bit of a sore point with me: this could be
solved so easily with a nice little macro <ducks>.  For the case where
you only want to print the name and value of a variable (as opposed to
that of an expression), you may find this little function helpful:

def print_variable(name, scope):
    print "%s = %r" % (name, scope[name])

You can call it like this:
    
print_variable('myTime', locals())

Not perfect, because you have to repeat locals() every time, but it
does save the repetition of the variable name.

Printing expressions can also be accomplished in a similar but more
dangerous[*] fashion:

def print_expression(expression, local_scope, global_scope=None):
    if global_scope is None:
        global_scope = globals()
    print "%s = %r" % (expression, 
                       eval(expression, local_scope, global_scope))

Example:

print_expression('i+1', locals())

[*] The use of eval here would make allowing user-entered expressions
    here very dangerous, but as long as as it is used as a debugging
    aid, with the expression as a literal string in the program, there
    should be no security issue.  I would never use either of these
    functions except as debugging aids anyway.

Regards,
    
-- 
--------------------------------------------------------------------
Aaron Bingham
Software Engineer
Cenix BioScience GmbH
--------------------------------------------------------------------




More information about the Python-list mailing list