dynamic assigments
Seldon
seldon at katamail.it
Fri Mar 25 08:29:20 EDT 2011
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 ?
More information about the Python-list
mailing list