nice python solution

Terry Reedy tjreedy at home.com
Wed Nov 21 02:35:04 EST 2001


"Tom Loredo" <loredo at astro.cornell.edu> wrote in message
news:3BFB237B.3FC46A84 at astro.cornell.edu...
> Steve Holden wrote:
> >
>
> > >   locals()[['a','b'][idx]] = val
> > >
> > This is absolutely verboten. I quote from Section 2.3 of the 2.0
manual, but
> > I don't think anything has changed since: """locals ()
> > Return a dictionary representing the current local symbol table.
Warning:
> > The contents of this dictionary should not be modified; changes
may not
> > affect the values of local variables used by the interpreter.
> > """

'verboten' is not quite right.  The statement is legal, but may not do
what one expects -- ie, it may be equivalent to 'pass'.

> But the code only modifies one of the references "a" or "b",

I am not quite sure what you mean by this.

> not  the locals dictionary.  Or am I missing something?

Look again.  The statement above is equivalent to

adict = locals()
key = ['a','b'][idx]
adict[key] = value
del adict, key

Unless adict *is* the local namespace (which it will not be inside a
function), the above is equivalent to 'pass' and not

if not idx": a = value
else:          b = value

as intended.

Terry J. Reedy







More information about the Python-list mailing list