Multiline template strings that don't break indentation

Boris Zbarsky bzbarsky at mit.edu
Tue Sep 9 07:39:37 PDT 2014


On 9/9/14, 4:18 AM, Andy Earnshaw wrote:
> It could be that I'm the only person who is this fussy and it doesn't
> bother anyone else, but I hope that's not the case.

We ran into this with Python multiline strings as well when we were 
working on Gecko's binding generator.

We (specifically Jason Orendorff) ended up implementing a "dedent" 
function which basically strips off the leading newline, if any, and 
then measures the number of spaces at the start of the string and 
removes that many spaces from each line.  So you can do:


   def foo():
       return dedent(
         """
         This is a string that will end up
         with no spaces at the beginnings of
         most of its lines.
           Except this one!
         """)

This worked great for our line-oriented (because they're C++ code or 
code templates) strings...

This addition definitely reduced the amount of concatenation we ended up 
doing.

-Boris


More information about the es-discuss mailing list