Creating variables from dicts

Luis M. González luismgz at gmail.com
Wed Feb 24 08:41:08 EST 2010


On Feb 24, 8:48 am, Bruno Desthuilliers <bruno.
42.desthuilli... at websiteburo.invalid> wrote:
> Luis M. Gonz lez a crit :
> (snip)
>
> > Alright, this is what the docs say about locals:
> > "Note
> > 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().
>
> > Note
> > 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).
>
> Because at the top level, locals and globals are the same thing.
>
> > And what about the trick of updating globals? Is it legal?
>
> It's legal, but it's (usually) a very bad idea - at the top-level, it
> harms readability, and from within a function it's doubly bad
> (readibility + "globals are evil").
>
> Now as usual with GoldenRules(tm), it's meant to be broken - once you do
> know why you shouldn't _usually_ do it.
>
>   for the very same reasons global
>
>
>
> > If not, is
> > there any "legal" way to do what the OP needs?
>
> > Luis

I still don't understand why is it a bad idea in the case of
globals().
This is the only way I know to define variables programatically in the
top-level namespace, without having to do it manually one by one.
I don't see the readability problem either.
Talking about Goldenrules(tm), what's the recomended way to do it?

Luis



More information about the Python-list mailing list