[Python-ideas] triple-quoted strings and indendation
Matthias Lehmann
mat at matlehmann.de
Wed May 11 18:44:04 CEST 2011
Hi all,
two times in one day I read about the problems of triple-quoted strings
and indendation (one time on stackoverflow, one time one this list).
Python is well known for its readability and its use of idendation to
this end. But with triple-quoted strings, nice indendation is not
possible without the need to post-process the resulting string.
Problem
=======
Most often, the desired result of
>>> some_string = """Hello
... World."""
is simply
Hello
World
instead of
Hello
World.
Idea
=====
What about the idea, to use a string-flag to indicate, that the
triple-quoted string is to be trimmed. Like:
>>> some_string = t"""Hello
... World."""
This would blend in with the 'u' and 'r' flags that already exist.
The triple-quoted string is trimmed to remove all whitespace up to the
column where the first line of the string started OR all common
whitespace of the subsequent lines, if the subsequent lines start on a
column before the first line. The second rule makes it possible to also
write:
>>> some_string = t"""Hello
... World."""
Pros
=====
The advantages above textwrap.dedent are:
1) textwrap.dedent only removes whitespace common to ALL lines, so to
achieve the desired result, one has to add an additional newline
>>> some_string = """
... Hello
... World."""
>>> result = textwrap.dedent(some_string)[1:]
2) Also, it does not work, if one actually does want some common
whitespace before all lines:
>>> some_string = """
... Hello
... Wold."""
>>> result = textwrap.dedent(some_string)[1:]
gives again
Hello
World
which is not, what I wanted. But
>>> some_string = t""" Hello
... World."""
would give
Hello
World.
3) And finally to quote a post from earlier today
"I know about textwrap.dedent, but having to use a
Python function call to code a literal has always made me
uncomfortable."
Problems
=========
Common indendation style for triple-quoted string (as far as I know) is
>>> foo = """blubber
... bla""" (align to first quote-char)
but with this auto-trimming, it would look better to use
>>> foo = t"""blubber
... bar""" (align to first char after triple quotes)
The other stlye would still work, though - as long as one does not want
to preserve leading whitespace.
Maybe the t flag could also cause a leading and trailing newline to be
removed, so that
>>> foo = t"""
... Hallo
... World.
... """
would also result in
Hello
World.
Maybe something like this has been proposed before - please be kind, if
it is an old hat.
Mat
<javascript:void(0);>
More information about the Python-ideas
mailing list