Newbie question
Josiah Carlson
jcarlson at uci.edu
Tue Nov 2 11:40:18 EST 2004
Alexander Stante <mrpac at gmx.de> wrote:
>
> On Mon, 01 Nov 2004 23:30:17 -0800, Uday wrote:
>
> > My problem is that I need to dynamically generate a unique
> > variable within a for loop in Python. The name of the variable
> > should be appended by the index of the loop.
> I think exec is what you want:
>
> for x in range(10):
> exec "var_%d = %d" % (x, x)
>
> This creates var_0 ... var_9 and assigns them the value of the index. exec
> executes strings which can be dynamically created at runtime. Okay, I
> guess performance isn't very well but if it is not crucial, who cares?
While exec works here, using exec as a hammer to do anything that
requires changing names isn't necessary. Being that the original poster
just wants to create and access certain names, a dictionary is perfect.
d = {}
for i in xrange(10):
d['var_name_%i'%i] = #whatever
Thomas Guettler <guettli at thomas-guettler.de> wrote:
> the best solution is to use a dictionary:
[snip]
Agreed.
> or you can do this:
> locals()["task_id"] # locals gives you a dictionary of the local vars
Kind of a hammer, but it does work. Though considering that one has to
later access those variables, he would then need to use locals()[varname],
which is no better than just using a dictionary in the first place.
> If you have a object you can use getattr()
>
> # myobj.task_id
> getattr(myobj, "task_id")
Don't forget setattr(). This pair is basically what the original poster
asked for.
- Josiah
More information about the Python-list
mailing list