[Python-ideas] Multi-line strings that respect indentation

Jared Grubb jared.grubb at gmail.com
Fri Nov 5 21:43:35 CET 2010


I like the idea of have d""" as the marker, as I've often wanted this for writing out custom HTML or source code.

But, would the level of dedent be based on the level of indent of the code line containing the d""" marker? If so, would you want a parsing/syntax error if the string violated the indentation levels of the surrounding code? (the dedent would have to take place post-parsing, since the grammar knows nothing about INDENT tokens inside strings, so it's not truly a "parser" error).

The easiest would be to do the equivalent of dedent and take the longest common whitespace length. But, the purist in me would kinda hope that if, for example, the code was indented to column 8 but the text was all at column 12, that the resulting string would have 4 leading spaces on each line.

Jared

On 5 Nov 2010, at 07:45, Nick Coghlan wrote:

> On Fri, Nov 5, 2010 at 11:10 AM, Stephen J. Turnbull <stephen at xemacs.org> wrote:
>>  > To me, this is rather ugly because it messes up the indentation of
>>  > some_func(). Suppose we could have a multiline string, that when started on
>>  > a line indented four spaces, ignores the first four spaces on each line of
>>  > the literal when creating the actual string?
>> I don't think the function call is ugly enough to fix with syntax.
> 
> I do use the textwrap.dedent workaround myself, but I think it is
> sufficiently flawed for a proper fix to be worth considering:
> 
> 1. It doesn't work for docstrings (as Tal pointed out)
> 2. It postpones until runtime an operation that could fairly easily be
> carried out at compile time instead
> 
> Note that a method on str objects fixes none of those problems, so
> isn't much of a gain from this point of view. As new string prefix
> would handle the task nicely, though. I personally like "d for
> dedent", with all d-strings (even single-quoted ones) being implicitly
> multiline as the colour for that particular bikeshed:
> 
> def some_func():
>   x, y = process_something()
> 
>   val = d"\
>   <xml>
>     <myThing>
>       <val>%s</val>
>       <otherVal>%s</otherVal>
>     </myThing>
>   </xml>
>   ") % (x, y)
> 
>   return val
> 
> I'm no more than +0 on the idea though. It strikes me as an awful lot
> of effort in implementing, documenting and promoting the idea for
> something that provides at best a minimal improvement in aesthetics
> and performance.
> 
> Cheers,
> Nick.
> 
> -- 
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas




More information about the Python-ideas mailing list