help

Steve Holden sholden at holdenweb.com
Sun Sep 29 06:18:34 EDT 2002


"Juliana Braga" <juliana at pdi.inpe.br> wrote in message
news:amqclg$6uu$1 at server.ltid.inpe.br...
> I need help.
> For example:
> x = ‘name1’
> How can I get the value of variable x (in this case the value of variable
x
> is ‘name1’). After , I’d like to do this:
> value of variable x = ‘teste’.
>

Juliana:

Your question is a little difficult to understand, so you may get several
answers. I suspect that what you were looking for is:

>>> x = 'name1'
>>> exec x + "= 'teste'"
>>> name1
'teste'
>>>

While this works, however, please remember that almost all such uses of
"exec" are simply making trouble for you as a programmer. The code must be
compiled at run-time, and whenever you need to access the variables you
create in this way you have to resort to further use of the exec statement.

It will probably be more appropriate to use a dictionary to hold the values
you create. A dictionary can use many different datatypes as keys, and in
particular strings are fine. So you might want to try something like:

>>> adict = {}
>>> adict[x] = "teste"
>>> adict["name1"]
'teste'
>>>

There's a lot of similarity between dictionaries and Python namespaces (for
the altogether predictable reason that Python currently *uses* dictionaries
to implement namespaces). When you want to use program-determined "variable
names" then a dictionary is often the solution.

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------






More information about the Python-list mailing list