setting variables in the local namespace

Gabriel Genellina gagsl-py2 at
Tue Oct 13 18:38:21 CEST 2009

En Tue, 13 Oct 2009 13:05:03 -0300, Chris Withers <chris at>  

> What I'd be looking for is something like:
> locals()[name]=value
> ...or, say:
> setattr(<somethingspecial>,name,value)
> Now, I got horribly flamed for daring to be so heretical as to suggest  
> this might be a desirable thing in #python, so I thought I'd ask here  
> before trying to take this to python-dev or writing a PEP:
> - what is so wrong with wanting to set a variable in the local namespace  
> based on a name stored in a variable?

In principle, nothing. But the local namespace is highly optimized: it is  
not a dictionary but a fixed-size C array of pointers. It's not indexed by  
name but by position. This can be done because the compiler knows (just by  
static inspection) which names are local and which aren't (locals are the  
names assigned to).
If you could add arbitrary names to the local namespace, the optimization  
is no more feasible. That's why "from foo import *" issues a warning in  
2.x and is forbidden in 3.x, and locals() isn't writable in practice.

> - have I missed something that lets me do this already?

Use your own namespace. You may choose dict-like access, or attribute-like  

class namespace:pass
ns = namespace()

ns.order = .....
setattr(ns, variablename, ......)
ns.area = ns.height * ns.width
ns = {}
ns['order'] = ...
ns[variablename] = ...
ns['area'] = ns['height'] * ns['width']

Or, see some recent posts about "dictionary with attribute-style access".

Gabriel Genellina

More information about the Python-list mailing list