Newbie question

Thomas Guettler guettli at thomas-guettler.de
Tue Nov 2 02:49:22 EST 2004


Am Mon, 01 Nov 2004 23:30:17 -0800 schrieb Uday:

> Hi,
>   I would like to know how can I create and assign variables by 
> de-referencing the values in other variable in Python. 
> 
> I can illustrate what I mean by an example of perl
> 
> $a = "task_id";
> $i = "1";
> $c = $a."_".$i;
> $$c = 2;
> print "$task_id_1\n";
> # Gives the answer as 2
> 
> 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. 

Hi,

the best solution is to use a dictionary:
myvars={}
myvars["task_id"]=....


or you can do this:
locals()["task_id"] # locals gives you a dictionary of the local vars


If you have a object you can use getattr()

# myobj.task_id
getattr(myobj, "task_id")

HTH,
 Thomas





More information about the Python-list mailing list