add an indent to a stream
Dave Brueck
dave at pythonapocrypha.com
Mon Mar 10 17:00:46 EST 2003
On Mon, 10 Mar 2003, Manuel Garcia wrote:
> On Mon, 10 Mar 2003 08:55:26 -0800 (PST), Dave Brueck
> >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.
Yes, but these are all _minor_ tweaks. My point was simply that you don't
need to manage all the softspace/comma stuff yourself - to me it just
seemed like a complex solution when you can get essentially the same thing
with far simpler and far less code.
> 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.
Sorry, I didn't realize I had to be THAT precise. ;-) I know it's not 100%
equivalent - I shortened it for the sake of focusing on what I took to be
the important part.
-Dave
More information about the Python-list
mailing list