Triple quoted string in exec function ?

Rob Williscroft rtw at freenet.co.uk
Wed Dec 31 03:49:41 CET 2008


Steven D'Aprano wrote in news:016abfa1$0$6988$c3e8da3 at news.astraweb.com in 
comp.lang.python:

> On Tue, 30 Dec 2008 15:35:28 -0600, Rob Williscroft wrote:
> 
>> Stef Mientki wrote in news:mailman.6399.1230668197.3487.python-
>> list at python.org in comp.lang.python:
>> 
>>>>> And, by the way, exec is a *statement*, not a function!
>>>>>     
>>>       exec ( Init_Code, PG.P_Globals )
>>> 
>>> I've really doubt that this is a statement, unless I don't understand
>>> what a statement is.
>>>>>     
>>>>>     
>>> 
>> In python 2.x the above is a statement that is passed a tuple:
>> 
>>          http://docs.python.org/reference/simple_stmts.html#exec
> 
> 
> The documentation doesn't say anything about it accepting a tuple as an 
> argument. The tuple argument works in both 2.5 and 2.6. Curious.
> 

My mistake, it is also behaving as a function:

    	http://docs.python.org/dev/3.0/whatsnew/3.0.html#removed-syntax

    	Removed keyword: exec() is no longer a keyword; it remains 
    	as a function. (Fortunately the function syntax was also accepted 
    	in 2.x.) Also ...

Though that was the only documentation of it I found in a brief 
web search.

> I was also surprised by this behaviour:
> 
>>>> g, l = {}, {}  # no globals, no locals
>>>> exec "x = 1" in g, l
>>>> l
> {'x': 1}
>>>> g.keys()
> ['__builtins__']
> 
> I see *now* that this is documented:
> 
> "...the current implementation MAY add a reference to the dictionary of 
> the built-in module __builtin__ under the key __builtins__ (!)."
> [emphasis added]
> 
> but it's still rather disconcerting. That means that:
> 
> exec "some potentially dangerous code" in {}, {}
> 
> isn't as safe as I thought it was.

AIUI it isn't meant to be safe, it provides some data hiding
that is useful for programming purposes but isn't much use
for security. 

Another example of a security hole:

>>> def f():
...   print "f()"
...
>>> exec "from __main__ import f; f()"
f()
>>>
    	
Rob.
-- 
http://www.victim-prime.dsl.pipex.com/



More information about the Python-list mailing list