This is Python code (!):
and here is the class (concise, and you can even pass it another stream object):
cout << "hello, world" << nl cout << "Tuples:" << (5 , 6, 7) << nl cout << "Lists:" << [5 , 6, 7] << nl cout << "The number, " << 1+1 << ", bigger than " << 1.0/5.0 << nl print "The number, %s, bigger than %s" % (1+1, 1.0/5.0) print "The number," , 1+1 , ", bigger than" , 1.0/5.0 # The 2nd is inelegant in my opinion. # I currently use the 3rd, but note that it inserts spaces, so it prints something different.
The recipe given in the Cookbook was longer, less clean (endl was an IoModifier object rather than '\n'), and used '%s' % obj instead of str(obj). I prefer my approach. I'm sure you could add all sorts of other "useful" features.
import sys class OStream(): def __init__(self, output=None): if output is None: output = sys.stdout self.output = output def __lshift__(self, obj): self.output.write(str(obj)) return self cout = OStream() nl = '\n'
Have you ever thought it is weird that left-shift means print? Actually, cout << "hello" is a lot nicer to type than cout("hello"), to me at least, so I don't really mind. Coming up next: subclassing list so that mylist << 4 does mylist.append(4) ... and mylist >> 0 does mylist.pop(0). (Just kidding).