Little Q: how to print a variable's name, not its value?
Ron_Adam
radam2 at tampabay.rr.com
Tue Mar 29 14:28:48 EST 2005
On Tue, 29 Mar 2005 11:23:45 -0500, Bill Mill <bill.mill at gmail.com>
wrote:
>On Tue, 29 Mar 2005 14:34:39 GMT, Ron_Adam <radam2 at tampabay.rr.com> wrote:
>> On 28 Mar 2005 23:01:34 -0800, "Dan Bishop" <danb_83 at yahoo.com> wrote:
>>
>> >>>> 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
>>
>> Fred = 5
>> John = 8
>> Winner = John
>>
>> Both John and Winner are pointing to the literal '8'.
>
>ummm, yes, of course they are. What's your point?
Hi Bill,
My point is if you look up the name and print it, you may get.
Instead of:
Fred has 5 points
John has 8 points
You could get:
Fred has 5 points
Winner has 8 points
Or something else depending on how many references you made to the
value 8.
>> Mixing data and program code, ie.. variable names as data, is not a
>> good idea.
>
>Down with eval! Exile exec! A pox on both their houses!
>
>(i.e. I respectfully disagree that mixing data with program code is a bad idea)
(I respectfully acknowledged your opinion.)
To be fair, it's not always bad. But in most cases it is better not
too.
I wasn't referring to using exec or eval, but to directly using data
values in the program code.
Here's an example of mixing data and code. If I write a program that
checks a list for specific names and prints corresponding value for
each.
I would not do this: ( Lots of stuff wrong with this example! )
playerlist = ['John','Bob','Fred']
John = 6
Bob = 8
Fred = 0
for name in playerlist:
if item == 'John':
print 'John', John
if item == 'Bob':
print 'Bob', Bob
This is only good for one set of data, and each time my data changes,
I would need to rewrite the program code also. This has data as
program code in both the variables and in the comparisons.
Not mixing data and code:
playerlist = {'John':6, 'Bob':8, 'Fred',0}
players = ['John', 'Bob']
for name in players:
print name, playerlist[name]
This does the same thing as above, but data and program code are not
mixed. It's much easier to maintain and reuse.
Ron
>Peace
>Bill Mill
>bill.mill at gmail.com
More information about the Python-list
mailing list