exec globals and locals

Quentin Lampin quentin.lampin at gmail.com
Wed Sep 2 13:54:51 CEST 2009


Hi,
Being fairly new to Python, I'm trying to figure out the best way to use the
exec statement and I must admit that I am a bit lost.

Consider this case:
exec "print 'a'" in {},{}   [exp.1]
It means  that I'm (kindly) asking the interpreter to execute the code
string  "print 'a'" with empty globals and locals.
Considering that globals and locals are empty, I would expect [exp.1] to
raise an exception about 'print' not being known.
However, the evaluation of [exp.1] produces an output...

>>> exec "print 'a'" in {},{}
a

So, I decided to read more attentively the documentation and here is what
I've found:

"""
As a side effect, an implementation may insert additional keys into the
dictionaries given besides those corresponding to variable names set by the
executed code. For example, the current implementation may add a reference
to the dictionary of the built-in module __builtin__ under the key
__builtins__ (!).
"""

Putting aside the fact that implementation specifics are evil, I would like
to know if there is one way to force builtins not to be added to the scope?
I would rather add this by myself which, in my opinion, is a more explicit,
thus more pythonic, way of doing.

Any comment on this?

Regards,

Quentin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090902/c1c093dd/attachment.html>


More information about the Python-list mailing list