Here's a hack I read about in the Python Cookbook. This one's for everyone who dislikes C++ :) The idea is to allow syntax like "cout << x" in Python. I liked the idea so I put together a simpler and cleaner implementation.
This is Python code (!):
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.
and here is the class (concise, and you can even pass it another stream object):
def __init__(self, output=None):
if output is None: output = sys.stdout
self.output = output
def __lshift__(self, obj):
cout = OStream()
nl = '\n'
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.
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).