print stream behavior
Peter Otten
__peter__ at web.de
Wed May 27 13:52:25 EDT 2009
Andreas Kraemer wrote:
> I don't understand the behavior of the print statement when streaming
> to a "file-like" object. From the documentation at
> http://www.python.org/doc/2.4.4/ref/print.html 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")?
This is a longstanding quirk of the CPython implementation. The
PRINT_ITEM_TO opcode triggers a PyFile_WriteObject() call which in turn does
the C equivalent of
if isinstance(f, file):
file.write(f, s)
else:
write = getattr(f, "write")
write(s)
Therefore subclasses of file will always use file.write() when invoked via
'print'.
You can avoid that by writing a wrapper instead of a subclass:
class File(object):
def __init__(self, *args):
self._file = open(*args)
def write(self, s):
self._file.write(s)
# add other methods as needed
Peter
More information about the Python-list
mailing list