programmatically define a new variable on the fly

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Aug 10 06:10:53 EDT 2007


Lee Sander a écrit :
> Hi,
> 
> I would like to define a new variable which is not predefined by me.
> For example,
> I want to create an array called "X%s" where "%s" is to be determined
> based on the data I am processing. So, for example, if I the file
> I'm reading has
> g 99
> on the first line, I want to create a new variable  called "Xg" whose
> length
> is 99.
> I tried eval("Xg=[0]*99") but that did not work.
> 
> any help would be greatly appreciated

As others already pointed out, the canonical solution is to use a dict, 
and it's almost always the best solution - a variant being to use an 
object (eventually a module object) and dynamically add attributes to it 
using setattr()[1].

Now, for the corner case where you *really* want to dynamically create 
new names in the module itself, the solution is to use exec. But I would 
definitively *not* recommand this solution unless you really know what 
you're doing and why you're doing it.

For the record, I did use this last solution twice in seven years. And 
it was mostly to avoid repeating boilerplate code in some low-level 
module of a framework. Definitively not a common case...


[1] which, FWIW, doesn't make much differences since attributes are 
stored in dicts....

> Lee
> 



More information about the Python-list mailing list