Creating variables from dicts

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Feb 24 20:04:54 EST 2010


On Wed, 24 Feb 2010 02:58:38 -0800, Luis M. González wrote:

> I wonder why updating locals(), not from within a function, works (at
> least in my interactive session).

Because if you're in the global scope, locals() returns globals(), which 
is a real namespace and modifying it works.

Inside a function, locals() returns a dict which is a *copy* of the 
function namespace. The reason for this is that local namespaces are not 
actually dicts, and you can't modify them except by actually assigning 
and deleting names in code.


> And what about the trick of updating globals? Is it legal? If not, is
> there any "legal" way to do what the OP needs?

Yes, it is legal to modify globals(). It's just a dict, you can even do 
this:

>>> globals()[2] = 4
>>> globals()[2]
4

although that's a pretty useless trick.

But whether you should is another story. I won't say you should NEVER do 
so, but it should be rare to use global variables, and even rarer to 
create them programmatically. The better solution is almost always to 
create your own namespace, namely a dict, and use that explicitly.


-- 
Steven



More information about the Python-list mailing list