Namespaces, multiple assignments, and exec()

Luis M. González luismgz at gmail.com
Sat Dec 20 10:44:03 EST 2008


On Dec 19, 11:34 pm, John O'Hagan <resea... at johnohagan.com> wrote:
> I have a lot of repetitive assignments to make, within a generator, that use a
> function outside the generator:
>
> var1 = func("var1", args)
> var2 = func("var2", args)
> var3 = func("var3", args)
> etc...
>
> In each case the args are identical, but the first argument is a string of the
> name being assigned. It works fine but I'd like to reduce the clutter by
> doing the assignments in a loop. I've tried using exec():
>
> for name in name_string_list:
>     exec(name + ' = func(\"' + name + '\", args)')
>
> but in the local namespace it doesn't understand func(), and if I give it
> globals() it doesn't understand the args, which come from within the
> generator.
>
> What's a good way to do this kind of thing?
>
> Thanks,
>
> John

Why don't you just use a dictionary?

d = {}

for name in name_string_list:
     d[name] = func(name, args)

Luis



More information about the Python-list mailing list