inherit from file and create stdout instance?

MisterPete pete.losangeles at gmail.com
Tue May 15 19:38:14 EDT 2007


> Your code works for me:
>
> import sys
>
> class Output(file):
>     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)
>
> o = Output()
> o.write("this goes to a console window")
>
> f = open("aaa.txt", "w")
> o = Output(f)
> o.write("this goes to a file")

  I could make wrappers around all of the file methods but that kind
of defeats the purpose of inheriting from file.  It's kind of odd to
inherit from file but then keep a file object (although then it would
at least pass any isinstance(object, file) tests at least) and
overwrite every single method.  I'd prefer that I inherit from file
and just get flush and next and everything for free (and any new
methods if they were added).

  What I'm really looking for is to make a copy of the sys.stdout
object but make it an Output object.  If the file object just had a
__dict__ with a buffer I could grab or something like that it wouldn't
be too tough.  Unfortunately I don't even know how I could make a copy
of sys.stdout since the copy module doesn't work for file objects.

Thanks,
Pete




More information about the Python-list mailing list