embedding python in python

Jeff Shannon jeff at ccvcorp.com
Fri Oct 1 02:17:06 CEST 2004


Maurice LING wrote:

> Hi,
>
> Sorry, I have another problem here. Given this snipplet,
>
> >>> def b(s):
> ...     exec(s)
> ...     exec('print "x= " + str(x)')
> ...
> >>> b('x = 10')
> x= 10
> >>>
> >>> print x
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'x' is not defined
> >>>
>
> Clearly, all the objects that were declared using exec() in function b 
> went out of scope, is there anyway to prevent this from happening?


 >>> myglobals = {}
 >>> mylocals = {}
 >>> exec "b = 1 + 2" in myglobals, mylocals
 >>> mylocals
{'b': 3}
 >>> exec "c = b * 2" in myglobals, mylocals
 >>> mylocals
{'c': 6, 'b': 3}
 >>> >>>

The exec statement can take an optional pair of dictionaries that it 
uses as the global and local namespaces to execute the given code in.  
This is *much* preferable to a bare exec for several reasons, one of 
them being exactly your issue, and another being safety -- since you 
must explicitly include any names that you want exec to use, it makes 
exec rather less likely to unintentionally stomp all over your namespace 
(or for malicious code to do certain types of harm).

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list