inherit from file and create stdout instance?

MisterPete pete.losangeles at gmail.com
Tue May 15 18:18:18 EDT 2007


How can I inherit from file but stil create an instance that writes to
stdout?
-----------
     I'm writing a file-like object that has verbosity options (among
some other things). I know I could just set self.file to a file object
rather than inheriting from file. I started with something like this
(simplified for clarity):

class Output(object):
    def __init__(self, file=sys.stdout, verbosity=1):
        self.verbosity = verbosity
        self.file = file

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

     but it is frustrating me that if I try to inherit from file it
works fine for regular files but I can't figure out a clean way to
instantiate an object that writes to stdout using sys.stdout.
something like the following:


class Output(object):
    def __init__(self, file=sys.stdout, verbosity=1):
        self.verbosity = verbosity
        self.file = file

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

I hope that's clear. Is it just a bad idea to inherit from file to
create a class to write to stdout or am I missing something? Any
insight is appreciated.

Thanks,
Pete




More information about the Python-list mailing list