[Tutor] Using exec with dict

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Jan 31 08:22:28 CET 2005



On Mon, 31 Jan 2005, [ISO-8859-1] Andr=E9 Roberge wrote:

> >/ I have a "robot" that can do some actions like "move()" and
> />/ "turn_left()".  I can program this robot using python like this:
> />/ =3D=3D=3D=3D
> />/ .def move_and_turn():
> [snip]//
> />/ The question I have is: how do I do this with an explicit dictionary.
> />/ I would *guess* that this is somehow equivalent to "how do I create a
> />/ dictionary that has access only to robot instructions [move(),
> />/ turn_left(), etc.] and Python's basic syntax" ... but I don't know ho=
w
> />/ to do this.
> /
> myGlobals =3D { 'move':move, 'turn_left':turn_left }
> exec code in myGlobals
>
> You don't need to add built-ins to myGlobals. Add whatever of your
> symbols you want the code to have access to.


Hello!

There's one subtlety here: exec() (as well as eval()) will automagically
stuff in its own version of a '__builtins__' dictionary if a binding to
'__builtins__' doesn't exist.  Here's a snippet from the documentation
that talks about this:

"""If the globals dictionary is present and lacks '__builtins__', the
current globals are copied into globals before expression is parsed. This
means that expression normally has full access to the standard __builtin__
module and restricted environments are propagated."""


This is a bit surprising, and caught me off guard when I played with exec
myself.  There are more details here:

    http://www.python.org/doc/ref/exec.html
    http://www.python.org/doc/lib/built-in-funcs.html#l2h-23


So if we really want to limit the global names that the exec-ed code sees,
you may want to add one more binding to '__builtins__':

###
>>> d =3D {}
>>> exec "print int('7')" in d
7
>>>
>>> d.keys()
['__builtins__']
>>>
>>>
>>> d2 =3D {'__builtins__' : {}}
>>>
>>> exec "print int('7')" in d2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<string>", line 1, in ?
NameError: name 'int' is not defined
###


Hope this helps!



More information about the Tutor mailing list