How do I do this? (eval() on the left hand side)

Steven Bethard steven.bethard at gmail.com
Tue Dec 7 17:50:59 EST 2004


It's me wrote:
> For simplicity sake, let's say I need to do something like this (for
> whatever reason):
> 
> <prompt for name of variable in someother program space you wish to
> retrieve>
> <go retrieve the value from that other program>
> <assign the retrieved value to a variable of the same name in Python>

If I had a situation like this, I'd probably store my 'variables' as 
keys in a dict, e.g.:

 >>> bindings = {}
 >>> for i in range(3):
... 	name = raw_input('Name: ')
... 	value = int(raw_input('Value for %r: ' % name))
... 	bindings[name] = value
...
<... after inputting 'eggs', '7', 'badger', '42', 'spam', '13' ...>
 >>> bindings
{'eggs': 7, 'badger': 42, 'spam': 13}

Once you have the 'variables' in a dict, you can just use the dict 
values in any expressions you need.

 >>> bindings['eggs'] * bindings['badger']
294

> I am just trying to understand the language and see what it can do.

Well, it can do a lot, but the folks on this list are helpful enough to 
mention when things you *can* do aren't necessarily things you *want* to 
do. ;)

Enjoy your explorations!

Steve



More information about the Python-list mailing list