[Python-Dev] Re: PEP 295 - Interpretation of multiline string constants
Michael Chermside
mcherm@destiny.com
Thu, 25 Jul 2002 14:01:42 -0400
Stephan Koltsov writes:
> I wrote a PEP, its number is 295, it is in attachment.
[... PEP on stripping newline and preceeding spaces
multi-line string literals ...]
I see ___ motivations for the proposals in this PEP, and propose
alternative solutions for each. NONE of my alternative solutions
requires ANY modification to the Python language.
--------
Motivation 1 -- Lining up line 1 of multi-line quotes:
Senario: - Use of string with things "lined up" neatly
>>> def someFunction():
... aMultiLineString = """Foo X 1.0
... Bar Y 2.5
... Baz Z 15.0
... Spam Q 38.9
... """
Notice how line 1 doesn't line up neatly with lines 2-4 because of
the indenting as well as the text assigning it to a variable. This
is annoying, and makes it awkward to read.
Solution: - Use a backslash to escape an initial newline
>>> def someFunction():
... aMultiLineString = """\
... Foo X 1.0
... Bar Y 2.5
... Baz Z 15.0
... Spam Q 38.9
... """
Notice that now everything lines up neatly. And we don't need to
modify Python at all for this to work.
--------
Motivation 2 - Maintaining Indentation
Senario: - Outdenting misleads the eye
>>> class SomeClass:
... def visitFromWaiter(self):
... if self.seated:
... self.silverware = ['fork','spoon']
... self.menu = """Spam
... Spam and Eggs
... Spam on Rye
... """
... self.napkin = DirtyNapkin()
Notice how the indentation makes it quite clear when we are inside a
class, a method, or a flow-control statement by merely watching the
left-hand margin. But this is crudely interrupted by the multi-line
string.
Solution: - Process the multi-line string through a function
>>> class SomeClass:
... def visitFromWaiter(self):
... if self.seated:
... self.silverware = ['fork','spoon']
... self.menu = stripIndent( """\
... Spam
... Spam and Eggs
... Spam on Rye
... """ )
... self.napkin = DirtyNapkin()
where stripIndent() has been defined as:
>>> def stripIndent( s ):
... indent = len(s) - len(s.lstrip())
... sLines = s.split('\n')
... resultLines = [ line[indent:] for line in sLines ]
... return ''.join( resultLines )
Notice how it is now NICELY indented, at the expense of a tiny
little 4-line function. Of course, there are faster and safer
ways to write stripIndent() (I, personally, would use a version
that checked that each line started with identical indentation
and raised an exception otherwise), but this version illustrates
the idea while being very, very readable.
----
In conclusion, I propose you use simpler methods available WITHIN the
language for solving this problem, rather than proposing a PEP to modify
the language itself.
-- Michael Chermside