Is it safe to modify the dict returned by vars() or locals()

Chris Rebert clp at rebertia.com
Mon Dec 1 16:21:31 EST 2008


On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch <jarausch at skynet.be> wrote:
> Hi,
>
> 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):
locals()
    Update and return a dictionary representing the current local symbol table.
    *Warning*:
    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
class blocks.

As the warning states, it modifying the dict doesn't really work
(except at the module level, but that's an implementation detail IIRC)
For example:
>>> def foo():
...     a = 3
...     l = locals()
...     l['a'] = 5
...     print a
...
>>> foo()
3

In any case, it'd be considered a bit of a hack.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> Many thanks for a hint,
> Helmut.
>
> --
> Helmut Jarausch
>
> Lehrstuhl fuer Numerische Mathematik
> RWTH - Aachen University
> D 52056 Aachen, Germany
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list