print doesn't respect file inheritance?
Terry Reedy
tjreedy at udel.edu
Sat Jul 26 00:27:06 EDT 2008
bukzor wrote:
> I was trying to change the behaviour of print (tee all output to a
> temp file) by inheriting from file and overwriting sys.stdout, but it
> looks like print uses C-level stuff to do its writes which bypasses
> the python object/inhertiance system. It looks like I need to use
> composition instead of inheritance, but thought this was strange
> enough to note.
>
> $python -V
> Python 2.5
>
> """A short demo script"""
> class notafile(file):
> def __init__(self, *args, **kwargs):
> readonly = ['closed', '__class__', 'encoding', 'mode', 'name',
> 'newlines', 'softspace']
> file.__init__(self, *args, **kwargs)
> for attr in dir(file):
> if attr in readonly: continue
> setattr(self, attr, None)
Drop the __init__ and give notafile a .write method.
Composition version inheritance is not the the real issue.
>>> class nf(object):
def write(s):
print(s)
print(s)
>>> print >>nf(), 'testing'
testing
testing
Now change nf.write to put the copy where you want it.
tjr
More information about the Python-list
mailing list