Exec Statement Question

7stud bbxx789_05ss at yahoo.com
Mon Apr 9 02:17:07 EDT 2007


On Apr 8, 11:31 pm, "Gregory Piñero" <gregpin... at gmail.com> wrote:
> I'm curious why this code isn't working how I expect it to:
>
> import sys
> d=3
>
> def func1(a,b,c):
>     print a,b,c,d
>     print sys.path
>
> exec "func1(1,2,3)" in {'func1':func1}
>
> ----
> returns:
> 1 2 3 3
> [ sys.path stuff ....]
>
> Since I'm telling exec to operate only within the context of the
> dictionary I give it, why does it still see sys.path and d?  I figured
> it would throw a NameError.
>
> Is there a way to call exec such that it won't have access to any more
> objects than I explicitly give it?
>
> Thanks,
>
> Greg

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.





More information about the Python-list mailing list