Exec Statement Question

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Apr 9 02:46:10 EDT 2007


7stud wrote:
> On Apr 8, 11:31 pm, "Gregory Piñero" <gregpin... at gmail.com> wrote:
> > Is there a way to call exec such that it won't have access to any more
> > objects than I explicitly give it?
>
> I think the way it works is that when the def is parsed, a function
> object is created and assigned to the name func1.  When the function
> object is created, d is "bound" to the global value 3, while a,b,c lie
> in wait for arguments to land in their gullets like venus fly traps.
> Your dictionary has a key whose value is a reference to the function
> object, which already has the value 3 bound to d.

Not exactly. As Georg Brandl said, the function has a reference to the
*globals* currently in use when it was defined, not directly to the
name "d".

To the OP: If you want a function with almost "empty" globals, compile
it the same way you used to execute it:

>>> text = """def func1(a):
...   print a
...   print b
...
... func1(3)
... print func1.func_globals.keys()
... """
>>>
>>> exec text in {}
3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<string>", line 5, in ?
  File "<string>", line 3, in func1
NameError: global name 'b' is not defined
>>> exec text in {"b": 123}
3
123
['__builtins__', 'func1', 'b']
>>>

I said *almost* empty because Python may insert other keys into the
globals, like __builtins__ above (see http://docs.python.org/ref/exec.html)

--
Gabriel Genellina




More information about the Python-list mailing list