modifying vars() dictionary?

Alex Martelli aleaxit at yahoo.com
Wed May 16 17:38:20 EDT 2001


"Lance E Sloan" <lsloan at umich.edu> wrote in message
news:mailman.990033564.4299.python-list at python.org...
>
> In the documentation, it says about vars():
>
>     The returned dictionary should not be modified: the effects on
>     the corresponding symbol table are undefined.
>
> Why are the effects undefined?  Why doesn't it always work to set
> a value for variable 'x' by assigning that value to the 'x' element
> of the dictionary from vars()?

Because the variables themselves may not be in a dictionary, and
surely not in the artificial 'vars()'-created dictionary... if vars()
must merge some locals and some globals to create it (when it's
called from a function that has locals).  Rebinding an entry in a
dictionary only affects that dictionary, because Python always
works that way -- no "side effects" on other items/references.

But sometimes it may be most efficient for vars() to give you the
actual dictionary (when there are no locals to be 'merged'...).  So
don't rely on rebiding items in vars() to NOT affect variables -- do
an explicit copy if you need one.


> I've noticed that sometimes it works and sometimes it doesn't.  In my
> small example it worked, but a colleague who asked me about this
> couldn't get it to work in a larger program.  I assume that I'm just
> lucky mine worked and that his problem may have something to do with
> the size of the symbol table or the kinds of objects in it.

Probably an issue of where vars() was called from, but that depends
on version-specific optimization issues.  A future version may well
do other optimizations...


Alex






More information about the Python-list mailing list