print doesn't respect file inheritance?

bukzor workitharder at gmail.com
Sat Jul 26 03:50:53 CEST 2008


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)


def main():
    n = notafile('/dev/stdout', "w")
    print vars(n)

    import sys
    sys.stdout = n
    print "Testing: 1, 2, 3..."


output:
{'__str__': None, 'xreadlines': None, 'readlines': None, 'flush':
None, 'close': None, 'seek': None, '__init__': None, '__setattr__':
None, '__reduce_ex__': None, '__new__': None, 'readinto': None,
'next': None, 'write': None, '__doc__': None, 'isatty': None,
'truncate': None, 'read': None, '__reduce__': None,
'__getattribute__': None, '__iter__': None, 'readline': None,
'fileno': None, 'writelines': None, 'tell': None, '__delattr__': None,
'__repr__': None, '__hash__': None}
Testing: 1, 2, 3...



More information about the Python-list mailing list