RFC PEP candidate: q'<delim>'quoted<delim> ?

Bengt Richter bokr at oz.net
Tue Mar 12 20:13:13 EST 2002


On Tue, 12 Mar 2002 22:18:09 +0000, philh at comuno.freeserve.co.uk (phil hunt) wrote:

>On 3 Mar 2002 09:50:58 GMT, Bengt Richter <bokr at oz.net> wrote:
>>Problem: How to put quotes around an arbitrary program text?
>
>I assume you mean here a *Python* program.
As the destination context, yes, but for the quoted matter, not necessarily.

>
>>    assert q'<-=delim=->'content here<-=delim=-> == 'content here' # this would be true
>>
>>without getting an error.
>
>Looks a bit complex. What if you have a quoted string inside a 
>quoted string, e.g, you want to quote this:
>
>   list = [1, q'|'string|, 3]
>
>if you just choose the same dewlimiter for the next time, it fails:
you wouldn't choose the same delimiter ;-) I.e., the main point of
using an (almost) arbitrary sequence of characters as a delimiter is
so you'll always have a choice of new delimiters if you need them to
wrap around text containing old ones.

>
>   q'|'list = [1, q'|'string|, 3]|
>
>as this would parse as the string "list = [1, q'" followed by a 
>syntax error. Of course, you could choose another delimeter, but 
>it'd be nice if this could be done automatically by a simple-minded
>program.
That could be arranged.
>
>Lisp is famous for being able to quote program text. The way it 
>manages it is by using (...); this is possible because any brackets 
>inside must match. Let's try this for Python, using {} instead of 
>(), to prevent it from looking like a function call:
>
>   list = [1, q{string}, 3]
>
>and:
>
>   q{list = [1, q{string}, 3]}
>
>This works. The reason it works is that the outer '{' only tries to 
>connect to the matching '}'. Inner braces are matched with 
>themselves; braces inside normal strings or comments are ignored.
>
But text with matching braces or matching whatever doesn't qualify as
arbitrary content. E.g., you should be able to quote a broken lisp program
if you want to.

>>Note the lack of quotes around the final delimiter string, since it itself is
>>the final delimiter. This can also be used to solve the final unescaped
>>backslash problem for quoting windows paths:
>>
>>    q'|'c:\foo\bar\|
>
>"""c:\foo\bar\""" and r"c:\foo\bar\" work just as well.
>
You didn't mean that ;-)

 >>> """c:\foo\bar\"""
 ...
 ... (it's waiting for three unescaped quotes in a row)
 ... """
 'c:\x0coo\x08ar"""\n\n(it\'s waiting for three unescaped quotes in a row)\n'
 >>>
 >>> r"c:\foo\bar\"
   File "<string>", line 1
     r"c:\foo\bar\"
                  ^
 SyntaxError: invalid token
 >>>

BTW,

    q'"""'c:\foo\bar\"""
and
    q'"'c:\foo\bar\"

would work, if you wanted to use """ and " as q-delimiters,
because *all* escape characters are ignored in the content.

>The best solution, of course, is to not use Windows.
>
You probably did mean that ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list