[Tutor] set locals

Steven D'Aprano steve at pearwood.info
Tue Dec 17 23:45:37 CET 2013


On Tue, Dec 17, 2013 at 04:52:25PM +0100, spir wrote:
> Hello,
> 
> is it at all possible to set new vars (or any symbol) into an existing 
> scope (typically locals())?

In general, no. The only time that writing to locals() is guaranteed to 
work is when you are in the top-level scope and locals returns the same 
dict as globals().


>     scope[name] = value
> raises by me an error like:
>     TypeError: 'mappingproxy' object does not support item assignment
> 
> I guess 'mappingproxy' is the implementation name of a scope (here, local), 

I cannot reproduce locals() returning a mappingproxy. What version of 
Python are you using, and how did you generate scope?


-- 
Steven


More information about the Tutor mailing list