Thursday, June 25, 2009

Python: C++ style cin, cout in Python

Ready to bring some flavor of C++ into python? If you like cout, cin in C++ and also a python programmer, you'd definitely like this snippet.
import sys
class ostream:
def __init__(self, file):
self.file = file

def __lshift__(self, obj):
self.file.write(str(obj));
return self
cout = ostream(sys.stdout)
cerr = ostream(sys.stderr)
endl = '\n'

x, y = 'Printing', 'like C++'
cout << x << " " << y << endl
Pretty cool, huh. I found this and a lot of other cool stuffs from Peter Norvig's blog. Its such a nice blog, just subscribed to it.

Back to Blogging

After a failed attempt last year to get back to blogging, I'm trying it again this year. I really wanted to get back, but got busy will...