print stream behavior

Andreas Kraemer akraemer at
Wed May 27 12:42:55 EDT 2009

I don't understand the behavior of the print statement when streaming
to a "file-like" object. From the documentation at I understand that the
file-like object needs to have a write() method that - I assume - is
called when the print statement is invoked. However, the piece of code
below does not behave as I expect.

F subclasses file and overwrites its write() method (simply printing
out a message and then calling the superclass's write()). Calling
write directly works as expected, using print does not.

Can anybody shed some light on what's happening under the hood (or how
to make it work with "print")?


Python 2.4.2 (#1, Jan 10 2008, 17:43:47)
[GCC 4.1.2 20070115 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class F(file):
...   def write(self,str):
...     print 'writing to %s: %s' % (,str)
...     file.write(self,str)
>>> f = F('test.txt','w')
>>> f.write('hallo')
writing to test.txt: hallo
>>> print >>f, 'good bye'

$ cat test.txt
hallogood bye

More information about the Python-list mailing list