[Python-ideas] triple-quoted strings and indendation
Terry Reedy
tjreedy at udel.edu
Thu May 12 00:17:40 CEST 2011
On 5/11/2011 12:44 PM, Matthias Lehmann wrote:
> 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.
Three partial solutions:
1. Strings are constants. Define them at the top of the module, in
global scope. I remember seeing this promoted as a good coding practice
once -- easy to find, modify, translate.
text = '''\
LIne 1
linklnlsf 2
and finally, we are done.
'''
I would consider this for strings, at least long strings, displayed to
end-users, with mnemonic names.
2. For doc strings, especially for top level classes, do not worry.
def whip_up(**args):
'''Return some delicious munchies made from inputs.
The keyword values should be edible and preferably yummy.
Whip_up will do the best it can which what you give it.
'''
Having help(whip_up) print
Return some delicious munchies made from inputs.
The keyword values should be edible and preferably yummy.
Whip_up will do the best it can which what you give it.
is not a problem. It might even be a virtue.
3. 'It is not necessarily so bad.' I have a test function with several
tests that compares an expected string, given as a literal, to actual
output captured with StringIO. Since this is a test_main in the file,
run with __name__ == '__main__', I do not want to put the strings in the
main part of the file (1 above). At first, the following bothered me.
expected = '''\
Line 1
Line 2
'''
I like Python's indentation! But it does not bother me so much anymore.
IDLE colors the literals green, so they can be semi-ignored. Having the
full screen width available can be a plus.
If I were using textwrap.dedent much, I might give it a short nickname
like 'de' would be visible while I want see it but ignorable when I do
not. If one wants a custom dedent rule, like the one you described,
write a custom function.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list