Little Q: how to print a variable's name, not its value?
Dan Bishop
danb_83 at yahoo.com
Tue Mar 29 02:01:34 EST 2005
stewart.midwinter at gmail.com wrote:
> No doubt I've overlooked something obvious, but here goes:
>
> Let's say I assign a value to a var, e.g.:
> myPlace = 'right here'
> myTime = 'right now'
>
> Now let's say I want to print out the two vars, along with their
names.
> I could easily do this:
> print "myPlace = %s, myTime = %s" % (myPlace, myTime)
>
> But that requires that I know in advance the name of the vars. What
if
> they are assigned dynamically. What I'm looking for is some method (
> call it f() ) that allows me to do this:
> print "%s = %s, %s = %s" % (f(myPlace), myPlace, f(myTime), myTime)
>
> Any ideas?
Try something like this:
>>> def print_vars(vars_dict=None):
... if vars_dict is None:
... vars_dict = globals()
... for var, value in vars_dict.items():
... print '%s = %r' % (var, value)
...
>>> myPlace = 'right here'
>>> myTime = 'right now'
>>> print_vars()
print_vars = <function print_vars at 0x401e0d84>
__builtins__ = <module '__builtin__' (built-in)>
myTime = 'right now'
myPlace = 'right here'
__name__ = '__main__'
__doc__ = None
More information about the Python-list
mailing list