Dynamic assignment

Steve Holden sholden at holdenweb.com
Fri Oct 26 05:08:32 CEST 2001


"Ingo Blank" <iblank at nospam.com> wrote in ...
> Hi,
>
> I want to dynamically create variables and assign values to them.
>
> I tried the following:
>
> >>> vn = "dynVar"
> >>> vv = 1
> >>> eval("%s=%d" % (vn,vv))
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "<string>", line 1
>     dynVar=1
>           ^
> SyntaxError: invalid syntax
>
> Q1: Why is the "syntax error" issued ?
> Q2: *HOW* do I achieve a dynamic assignment ?
>
>>> vn = "dynVar"
>>> vv = 1
>>> exec "%s=%d" % (vn, vv)
>>> print dynVar
1
>>>

eval() is a function that evaluates expressions. exec is a statement that
executes statements.

However, you should be very sure that this is really what you need, since
when you create variables dynamically like this you also have to access them
using dynamically constructed statements. It would, unless you have a
special reason for wanting to do it as above, be easier to use (say) a
dictionary and store values in there against string keys. Ultimately Python
namespaces and dictionaries aren't that different anyway... so think about
using

d = {}
d["dynVar"] = 1

and so on.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list