C++ style Stream Operators

Rainer Deyke root at rainerdeyke.com
Thu Feb 8 20:20:59 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?

File objects in Python are somewhat like 'streambuf's in C++.  Just write
your own class with a '__lshift__' that formats the text and writes it to a
file object:

class ostream:
  def __init__(self, buf):
    self.buf = buf
  def __lshift__(self, rhs):
    self.buf.write(str(rhs))

cout = ostream(sys.stdout)
cout << 'Hello world!\n'


--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list