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

Nick Coghlan ncoghlan at gmail.com
Fri Nov 5 15:45:56 CET 2010


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



More information about the Python-ideas mailing list