Python3 exec locals - this must be a FAQ
Helmut Jarausch
jarausch at skynet.be
Tue Feb 12 09:29:08 EST 2013
On Tue, 12 Feb 2013 08:27:41 -0500, Dave Angel wrote:
> On 02/12/2013 06:46 AM, Helmut Jarausch wrote:
>> Hi,
>>
>> I've tried but didn't find an answer on the net.
>>
>> The exec function in Python modifies a copy of locals() only.
>> How can I transfer changes in that local copy to the locals of my
>> function ** without ** knowing the names of these variables.
>>
>> E.g. I have a lot of local names.
>>
>> Doing
>>
>> _locals= locals()
>
> This doesn't copy everything. But perhaps you know that and you're just
> testing us.
No, I didn't know. And I'm bit surprised since this is recommend
several times, e.g. in "Python Essential Reference, 4th ed" by
David Beazley.
>
>> expr=compile(input('statements assigning to some local variables '),
>> 'user input','exec')
>> exec(expr,globals(),_locals)
>>
>> How can I "copy" the new values within _locals to my current locals.
>>
>> If I knew that Var1 has changed I could say Var1 = _locals['Var1']
>> but what to do in general?
>
> locals()["Var1"] = _locals["Var1"] will set the same Var1 local.
Thanks for this hint which surprises me again since I thought
locals() by itself is a copy only.
>
> So you might write a loop on _locals.
>
> But beware if someone has deleted one of the "variables" it may not do
> what you'd like. You cannot necessarily add back a local with the above
> syntax.
Does this mean that adding something completely new won't work?
Many thanks,
Helmut.
More information about the Python-list
mailing list