[Python-Dev] eval and triple quoted strings

Ron Adam ron3200 at gmail.com
Sat Jun 15 21:58:33 CEST 2013



On 06/14/2013 04:03 PM, PJ Eby wrote:
>> >Should this be the same?
>> >
>> >
>> >python3 -c 'print(bytes("""\r\n""", "utf8"))'
>> >b'\r\n'
>> >
>> >
>>>>> >>>>eval('print(bytes("""\r\n""", "utf8"))')
>> >b'\n'
> No, but:
>
> eval(r'print(bytes("""\r\n""", "utf8"))')
>
> should be.  (And is.)
>
> What I believe you and Walter are missing is that the \r\n in the eval
> strings are converted early if you don't make the enclosing string
> raw.  So what you're eval-ing is not what you think you are eval-ing,
> hence the confusion.

Yes thanks, seems like an easy mistake to make.

To be clear...

The string to eval is parsed when the eval line is tokenized in the scope 
containing the eval() function.  The eval function then parses the 
resulting string object it receives as it's input.

There is no mention of using raw strings in the docs on evel and exec.  I 
think there should be, because the intention (in most cases) is for eval to 
parse the string, and not for it to be parsed or changed before it's 
evaluated by eval or exec.

An example using a string with escape characters might make it clearer.

Cheers,
    Ron



More information about the Python-Dev mailing list