Creating variables from dicts
Luis M. González
luismgz at gmail.com
Wed Feb 24 11:58:38 CET 2010
On Feb 24, 7:44 am, Luis M. González <luis... at gmail.com> wrote:
> On Feb 24, 4:08 am, Steven D'Aprano
> <ste... at REMOVE.THIS.cybersource.com.au> wrote:
> > On Tue, 23 Feb 2010 20:44:10 -0800, Luis M. González wrote:
> > > On Feb 24, 1:15 am, Steven D'Aprano
> > > <ste... at REMOVE.THIS.cybersource.com.au> wrote:
> > >> On Tue, 23 Feb 2010 19:47:22 -0800, Luis M. González wrote:
> > >> > On Feb 23, 10:41 pm, Steven D'Aprano
> > >> > <ste... at REMOVE.THIS.cybersource.com.au> wrote:
> > >> >> On Tue, 23 Feb 2010 15:41:16 -0800, Luis M. González wrote:
> > >> >> > By the way, if you want the variables inside myDict to be free
> > >> >> > variables, you have to add them to the local namespace. The local
> > >> >> > namespace is also a dictionary "locals()". So you can update
> > >> >> > locals as follows:
> > >> >> > locals().update( myDictionary )
> > >> >> No you can't. Try it inside a function.
> > >> >> --
> > >> >> Steven
> > >> > Sure. Inside a function I would use globals() instead. Although I
> > >> > don't know if it would be a good practice...
> > >> Er, how does using globals change the local variables?
> > >> --
> > >> Steven
> > > Hmmm.... well, you tell me!
> > I'm not the one that said you can update locals! You said it. I said you
> > can't, because you *can't*. The docs warn that you can't change locals,
> > and if you try it, you will see that the docs are right.
> > >>> def test():
> > ... x = 1
> > ... locals().update(x = 2)
> > ... print x
> > ...
> > >>> test()
> > 1
> > > As I said, I don't know if this is the recomended way...
> > It's not recommended because it doesn't work.
> > --
> > Steven
> I guess I have to check the docs...
> Anyway, nobody wanted to update locals() from within a function here.
> Doing it outside of a function seems to work.
> And updating globals() works in any case, which is what the OP seems
> to need. Isn't it?
Alright, this is what the docs say about locals:
The built-in functions globals() and locals() return the current
global and local dictionary, respectively, which may be useful to pass
around for use as the second and third argument to exec().
The default locals act as described for function locals() below:
modifications to the default locals dictionary should not be
attempted. Pass an explicit locals dictionary if you need to see
effects of the code on locals after function exec() returns."
I wonder why updating locals(), not from within a function, works (at
least in my interactive session).
And what about the trick of updating globals? Is it legal? If not, is
there any "legal" way to do what the OP needs?
More information about the Python-list