[Python-Dev] str.dedent

Noam Raphael noamraph at gmail.com
Sat Nov 12 20:52:32 CET 2005


Following Avi's suggestion, can I raise this thread up again? I think
that Reinhold's .dedent() method can be a good idea after all.

The idea is to add a method called "dedent" to strings. It would do
exactly what the current textwrap.indent function does. The motivation
is to be able to write multilined strings easily without damaging the
visual indentation of the source code, like this:

def foo():
    msg = '''\
             From: %s
             To: %s\r\n'
             Subject: Host failure report for %s
             Date: %s

             %s
             '''.dedent() % (fr, ', '.join(to), host, time.ctime(), err)

Writing multilined strings without spaces in the beginning of lines
makes functions harder to read, since although the Python parser is
happy with it, it breaks the visual indentation.

On 9/15/05, Guido van Rossum <guido at python.org> wrote:
> From the sound of it, it's probably not worth endowing every string
> object with this method and hardcoding its implementation forever in C
> code. There are so many corner cases and variations on the
> functionality of "dedenting" a block that it's better to keep it as
> Python source code.

I've looked at the textwrap.dedent() function, and it's really simple
and well defined: Given a string s, take s.expandtabs().split('\n').
Take the minimal number of whitespace chars at the beginning of each
line (not counting lines with nothing but whitespaces), and remove it
from each line.

This means that the Python source code is simple, and there would be
no problems to write it in C.

On 9/15/05, Raymond Hettinger <raymond.hettinger at verizon.net> wrote:
>
> -1
>
> Let it continue to live in textwrap where the existing pure python code
> adequately serves all string-like objects.  It's not worth losing the
> duck typing by attaching new methods to str, unicode, UserString, and
> everything else aspiring to be string-like.
>
> String methods should be limited to generic string manipulations.
> String applications should be in other namespaces.  That is why we don't
> have str.md5(), str.crc32(), str.ziplib(), etc.
>
> Also, I don't want to encourage dedenting as a way of life --- programs
> using it often are likely to be doing things the hard way.
>
I think that the difference between "dedent" and "md5", "crc32" and
such is the fact that making "dedent" a method helps writing code that
is easier to read.

Strings already have a lot of methods which don't make code clearer
the way "dedent" will, such as center, capitalize, expandtabs, and
many others. I think that given these, there's no reason not to add
"dedent" as a string method.

Noam


More information about the Python-Dev mailing list