print stream behavior
Andreas Kraemer
akraemer at sbcglobal.net
Wed May 27 14:02:55 EDT 2009
On May 27, 10:52 am, Peter Otten <__pete... at web.de> wrote:
> 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
Thanks very much! That solves the mystery ...
More information about the Python-list
mailing list