Problem with exec

Peter Otten __peter__ at web.de
Fri Dec 16 10:22:38 EST 2005


Antoon Pardon wrote:

> And from the documentation 
> from exec I get the impression you can use it so that a function 
> will have temporarily a different reference to global namespace.

That impression confuses two things:

(1) A function object carries a global namespace with it. That namespace is
fixed when the function definition is executed, not when the function is
called.

(2) You may provide a global namespace to exec. What's in that may be
altered by rebinding operations (=, def, etc.) in the exec't string.
Functions defined here use that namespace as their global namespace while
functions just executed here don't.

If you could provide a function with a different namespace when it's called,
e. g

f() in namespace

would look up its globals in namespace, that might be an interesting concept
but it's not how Python works.

Peter




More information about the Python-list mailing list