getting the name of a variable
James_Althoff at i2.com
James_Althoff at i2.com
Thu Dec 6 13:33:54 EST 2001
Michael Hudson wrote:
>sandskyfly at hotmail.com (Sandy Norton) writes:
>> When I'm debugging I'm always sticking stuff like "print 'x:', x" in
>> my code. So is there a handy function that will print a variable
>> name and value such that:
>>
>> >>> def print_var_name_and_value(var):
>> "prints variable name : value"
>> <implemention>
>>
>> >>> variable = 'me var'
>> >>> print_var_name_and_value(variable)
>> variable : me var
>
>Not really. Hit google groups for more info. Some highlights:
>
>a gross implementation attempt by me:
>
>
http://groups.google.com/groups?selm=m38zytnexz.fsf%40atrus.jesus.cam.ac.uk
>
>a nice explanation of why this not really possible by /F:
>
>http://groups.google.com/groups?selm=3a03261b_1%40corp.newsfeeds.com
It seems though, for the narrow purpose requested here, if you are willing
to turn things around and pass the *name* of the variable instead of its
value then -- using nested scopes -- one could write something like:
>>> def prvar(x):
... print x, ':', eval(x)
...
>>> z = 1
>>> prvar('z')
z : 1
>>>
Might save a little bit of typing.
>>> def prvar(*varnames):
... for name in varnames:
... print name, ':', eval(name), ';',
...
>>> a = 1
>>> b = 2
>>> c = 3
>>> prvar('a','b','c')
a : 1 ; b : 2 ; c : 3 ;
Jim
More information about the Python-list
mailing list