namespace hacking question

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Thu Sep 30 19:36:49 CEST 2010


On 30 sep, 19:07, kj <no.em... at please.post> wrote:
> This is a recurrent situation: I want to initialize a whole bunch
> of local variables in a uniform way, but after initialization, I
> need to do different things with the various variables.
>
> What I end up doing is using a dict:
>
> d = dict()
> for v in ('spam', 'ham', 'eggs'):
>     d[v] = init(v)
>
> foo(d['spam'])
> bar(d['ham'])
> baz(d['eggs'])
>
> This is fine, but I'd like to get rid of the tedium of typing all
> those extra d['...']s.
>
> I.e., what I would *like* to do is something closer to this:
>
> d = locals()
> for v in ('spam', 'ham', 'eggs'):
>     d[v] = init(v)
>
> foo(spam)
> bar(ham)
> baz(eggs)
>
> ...but this results in errors like "NameError: global name 'spam' is
> not defined".
>
> But the problem is deeper than the fact that the error above would
> suggest, because even this fails:
>
> spam = ham = eggs = None
> d = locals()
> for v in ('spam', 'ham', 'eggs'):
>     d[v] = init(v)

The local namespace is not implemented as a dict - locals() only
returns a dict representation of it, so updating this dict has no
effect on the local namespace. This is documented FWIW.

>
> I also tried a hack using eval:
>
> for v in ('spam', 'ham', 'eggs'):
>     eval "%s = init('%s')" % (v, v)
>
> but the "=" sign in the eval string resulted in a "SyntaxError:
> invalid syntax".

eval only accepts expressions. You'd need exec here - but that's a bit
ugly.




More information about the Python-list mailing list