C++ style Stream Operators

Alex Martelli aleaxit at yahoo.com
Thu Feb 8 17:35:34 EST 2001


"Jim" <jimholliman at heartsoft.com> wrote in message
news:3a831395.0 at 216.0.152.7...
> I'd like to use C++style stream i/o operators, such as "file_object <<
> some_stuff" in my python code.
> IS this sort of operator setup and what modules would I need to take
> advantage of them if so?

You can get a somewhat similar look with the new-ish
    print >> file_object, some_stuff
syntax.  Or, go whole hog (the expression somehow
seems particularly appropriate) and write a class with
an overloaded __lshift__ operator:

class Stream:
    def __init__(self, file):
        self.file = file
    def __lshift__(self, stuff):
        self.file.write(str(stuff))
        return self
    def __repr__(self):
        return ''

import sys
cout = Stream(sys.stdout)

so you can code beauties like cout<<"Hi there!".  The
'return self' at the end of __lshift__ lets you chain your
'<<'s, and the __repr__ even lets you try it out at the
interactive interpreter command line.

I think you'd be very badly advised to pursue this route,
spending energy to enable doubtful syntax sugar which
many Pythonistas will find quite unpleasant, but, in any
case, Python offers you "enough rope to shoot yourself
in the foot" -- and you could argue that "print>>flob"
is a precedent that legitimates what you're doing:-).


Alex






More information about the Python-list mailing list