inherit from file and create stdout instance?

MisterPete pete.losangeles at gmail.com
Tue May 15 23:08:39 EDT 2007


On May 16, 1:50 pm, 7stud <bbxx789_0... at yahoo.com> wrote:
> >but it is frustrating me that if I try to inherit from file it
> >works fine for regular files
>
> I don't think that is correct characterization at all.  What really
> happens is that when you inherit from file, your class works when you
> send the __init__ method a string, i.e. a filename. sys.stdout is not
> a string.  Presumably, when you have a file object like sys.stdout
> already, you don't need to turn it into a file object, and therefore
> file's init() method is not defined to accept a file object.
>
> >Is it just a bad idea to inherit from file to
> >create a class to write to stdout or am I missing something?
>
> It seems to me that the very nature of a file object is to read and
> write to itself.  Yet, in some cases you want your file object to be
> able to write to another file object.   Why would you want your object
> to be a file object if you can't use any of its methods?

7stud,
I don't really want it to write to another file object, I'd like it to
work just like a file object except for some extra options like
verbosity. Similar to how sys provides stdout and stderr file objects
I would like to provide Output objects for stdout and stderr... but
without accepting a file object I'm not sure how I would instantiate
an Output object that writes to anything like stdout or stderr without
special casing them

Gabriel,
thanks for the suggestion! I think I'll go with an approach similar to
that :)  I guess I can't really get around using the stdout/stderr
file objects for writing to those buffers.

=============
oops, not that it really matters but I just realized that I cut and
pasted the same code twice in my original post.  I had meant to put
this as the second chunk of code

class Output(file):
    def __init__(self, name, mode='w', buffering=None, verbosity=1):
        super(Output, self).__init__(name, mode, buffering)
        self.verbosity = 1

    def write(self, string, messageVerbosity=1):
        if messageVerbosity <= self.verbosity
            super(Output, self).write(string)




More information about the Python-list mailing list