On 03/25/2011 06:29 AM, Seldon wrote: > Because I'm in this situation. My current code is of the form: > > var1 = func(arg=value1, *args) > .. > varn = func(arg=valuen, *args) > > where var1,..varn are variable names I know in advance and > value1,..valuen are objects known in advance, too; func is a long > invocation to a factory function. Each invocation differs only for the > value of the 'arg' argument, so I have a lot of boilerplate code I'd > prefer to get rid of (for readability reasons). > > I thought to refactor the code in a more declarative way, like > > assignment_list = ( > ('var1', value1), > ('var2', value2), > .. , > ) > > for (variable, value) in assignment_list: > locals()[variable] = func(arg=value, *args) > > My question is: what's possibly wrong with respect to this approach ?
Wouldn't it be easiest just to keep the variables in a dictionary or something, and then refer to them by key? funcs = {} for (variable, value) in assignment_list: funcs[variable] = func(arg=value, *args) print funcs['var1'] There doesn't seem to be any benefit to having things in the python namespace when for your purposes a dictionary would work very cleanly. -- http://mail.python.org/mailman/listinfo/python-list