Is it safe to modify the dict returned by vars() or locals()
clp at rebertia.com
Mon Dec 1 22:21:31 CET 2008
On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch <jarausch at skynet.be> wrote:
> I am looking for an elegant way to solve the following problem:
> Within a function
> def Foo(**parms)
> I have a list of names, say VList=['A','B','C1']
> and I like to generate abbreviation
> _A identical to parms['A']
Could you explain what you mean by that? Your sample code doesn't seem
to do any "abbreviation"...
Otherwise I don't see why you don't just have a proper parameter list.
> for that I could write
> def Foo(**parms) :
> for N in VList :
> if N in parms :
> vars()[N]= parms[N]
> else :
> vars()[N]= None
> Does this work, is it typical Python?
>From the docs (http://docs.python.org/library/functions.html):
Update and return a dictionary representing the current local symbol table.
The contents of this dictionary should not be modified; changes
may not affect the values of local variables used by the interpreter.
Free variables are returned by locals() when it is called in a
function block. Modifications of free variables may not affect the
values used by the interpreter. Free variables are not returned in
As the warning states, it modifying the dict doesn't really work
(except at the module level, but that's an implementation detail IIRC)
>>> def foo():
... a = 3
... l = locals()
... l['a'] = 5
... print a
In any case, it'd be considered a bit of a hack.
Follow the path of the Iguana...
> Many thanks for a hint,
> Helmut Jarausch
> Lehrstuhl fuer Numerische Mathematik
> RWTH - Aachen University
> D 52056 Aachen, Germany
More information about the Python-list