eval modifies passed dict

colas.francis at gmail.com colas.francis at gmail.com
Mon Apr 14 12:28:22 EDT 2008


On 14 avr, 18:05, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> Janto Dreijer <jan... at gmail.com> wrote:
> > It seems eval is modifying the passed in locals/globals. This is
> > behaviour I did not expect and is really messing up my web.py app.
>
> > Python 2.5.1 (r251:54863, Mar  7 2008, 04:10:12)
> > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
> >>>> d = dict(a=1)
> >>>> d.keys()
> > ['a']
> >>>> eval("a", d)
> > 1
> >>>> d.keys()
> > ['a', '__builtins__']
>
> > That can't be right.
>
> That can exactly be right.
>
> The current document is (I think) wrong or at the least misleading. It
> says:
>
> > If the globals dictionary is present and lacks '__builtins__', the
> > current globals are copied into globals before expression is parsed.
>
> I think it should say:
>
> > If the globals dictionary is present and lacks '__builtins__', the
> > current value of __builtins__ is added to globals before expression
> > is parsed.
>
> i.e. only a single variable is assigned, other globals aren't copied.

Indeed:

Python 2.5.1 (r251:54863, Mar  7 2008, 03:39:23)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> globals().keys()
['__builtins__', '__name__', '__doc__']
>>> b = 2
>>> d = {'a': 1}
>>> eval('a', d)
1
>>> d.keys()
['a', '__builtins__']




More information about the Python-list mailing list