Triple quoted string in exec function ?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Dec 30 20:15:35 EST 2008


On Tue, 30 Dec 2008 21:16:39 +0100, Stef Mientki wrote:


> I guess I've to remove all triple quoted strings from my code.

There's no problem with triple-quoted strings. You just have to quote 
them properly.


>>> text = """x = 1
... y = x+2
... del x
... print y
... """
>>> exec text
3


You can even embed triple-quoted strings inside the string to be executed.

>>> text = "s = '''%s'''" % """This is a
... triple quoted
... string"""
>>> 
>>> exec text
>>> s
'This is a\ntriple quoted\nstring'


If you're going to remove anything, I'd look at why you are using exec in 
the first place. To me, it's a code smell -- not necessarily wrong, but 
exec is awfully open to abuse and potential security flaws.


-- 
Steven



More information about the Python-list mailing list