Exec and namespaces

hnowak hnowak at cuci.nl
Tue Jul 24 09:10:53 EDT 2001


>===== Original Message From Aquarius <aquarius at kryogenix.org> =====
>I've got a CGI which reads a file and then execs its contents. The file
>defines a function, and that function can't find itself to call
>recursively; it gets a NameError.

>def main():
>    fp = open("foo.txt")
>    exec(fp.read())

Replace this by

    exec fp.read() in {}

and it should work fine.

The exec() call first creates the bar() function in the local mainspace,
i.e. the namespace of main(). So far, so good; calling bar() works too, but 
the recursive call fails, roughly because of the reasons you already 
mentioned: bar() is neither in the global nor in the local (in this case, in 
bar's) namespace, so a NameError is raised. (At least I *think* that's what 
happens. I'm not a language lawyer. ;-)

The Reference Manual says:

"In all cases, if the optional parts are omitted, the code is executed in the 
current scope. If only the first expression after in is specified, it should 
be a dictionary, which will be used for both the global and the local 
variables. If two expressions are given, both must be dictionaries and they 
are used for the global and local variables, respectively."

(I'm using Python 2.2a1 docs, Doc/ref/exec.html#l2h-365)

Specifying the "in {}" creates a temporary namespace for exec, which is used 
to define and look up the bar function.

HTH,

--Hans Nowak





More information about the Python-list mailing list