add an indent to a stream

Manuel Garcia news at manuelmgarcia.com
Mon Mar 10 15:11:48 EST 2003


On Mon, 10 Mar 2003 08:55:26 -0800 (PST), Dave Brueck
<dave at pythonapocrypha.com> wrote:
(edit)
>> class IndentStream:
>>     """Stream with indent at start of each line.
>>
>>     Indent can be a string or
>>     the number of spaces you wish to indent.
>>
>>     """
>>
>>     def __init__(self, indent='    ', stream=None):
>>         if stream is None:
>>             self._stream = sys.stdout
>>         else:
>>             self._stream = stream
>>         try:
>>             indent = ' ' * indent
>>         except TypeError:
>>             pass
>>         self._indent = indent
>>         self._nl_indent = '\n' + indent
>>         self._indent_size = len(indent)
>>         self._comma = 0
>>         self.softspace = 0
>>
>>     def write(self, s):
>>         comma = not s.endswith('\n')
>>         s = s.replace('\n', self._nl_indent)
>>         if not self._comma: s = self._indent + s
>>         if s.endswith(self._nl_indent): s = s[:-self._indent_size]
>>         self._stream.write(s)
>>         self._comma = comma
>
>Doesn't the above behave the same as:
>
>class IndentStream:
>    def __init__(self, indent='    ', stream=sys.stdout):
>        self.stream = stream
>        stream.write(indent)
>        self.indent = indent
>
>    def write(self, s):
>        self.stream.write(s.replace('\n', '\n' + self.indent))

Unfortunately, an indented line might be followed by a line that
should not be indented, so we would not want the extra 'self.indent'
at the end.  Like this:

    print 'normal'    
    print >> _indentstream, 'indent'
    print 'normal again'
    print >> _indentstream, 'indent again'
    print 'normal 3'

With extra bookkeeping:

normal
....indent
normal again
....indent again
normal 3

Without extra bookkeeping:

normal
....indent
....normal again
indent again
....normal 3

where we use periods instead of spaces.  Also I don't really want to
write an indent in the __init__, because I could be creating the
stream long before I use it, if I ever use it.

Also, I didn't want to use 'def __init__(... stream=sys.stdout)'
because sys.stdout might be overwritten by the user with a specialized
version some time after the class is created, because
'stream=sys.stdout' would be evaluated only once.

Manuel





More information about the Python-list mailing list