dynamic assigments

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Mar 25 09:13:44 EDT 2011


Seldon wrote:
> On 03/25/2011 12:05 AM, Steven D'Aprano wrote:
>> On Thu, 24 Mar 2011 19:39:21 +0100, Seldon wrote:
>>
>>> Hi, I have a question about generating variable assignments 
>>> dynamically.
>> [...]
>>> Now, I would like to use data contained in this list to dynamically
>>> generate assignments of the form "var1 = value1", ecc where var1 is an
>>> identifier equal (as a string) to the 'var1' in the list.
>>
>> Why on earth would you want to do that?
>>
>
> 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 ?
First thing, locals help states the following:
"Note The contents of this dictionary should not be modified; changes 
may not affect the values of local and free variables used by the 
interpreter"

http://docs.python.org/library/functions.html#locals

Can't you use something like

rootValues = { 'var1': 45, 'var2': 0, }

def func2x(x):
    return x*2

def main():
    mappedValues = {}
    for varName in rootValues:
        mappedValues[varName] = func2x(rootValues[varName])
        print  mappedValues[varName]

main()

 > 90
 > 0


JM



More information about the Python-list mailing list