Py3K: file inheritance

Ian Kelly ian.g.kelly at gmail.com
Fri Oct 21 02:50:35 EDT 2011


On Thu, Oct 20, 2011 at 10:17 PM, Yosifov Pavel <bulg at ngs.ru> wrote:
> Little silly example:
>
> class MyFile(file):
>  def __init__(self, *a, **ka):
>    super(MyFile, self).__init__(*a, **ka)
>    self.commented = 0
>  def write(self, s):
>    if s.startswith("#"):
>      self.commented += 1
>      super(MyFile, self).write(s)
>
> When I tried in Python 3.x to inherit FileIO or TextIOWrapper and then
> to use MyFile (ex., open(name, mode, encoding), write(s)...) I get
> errors like 'unsupported write' or AttributeError 'readable'... Can
> you show me similar simple example like above but in Python 3.x?

class MyTextIO(io.TextIOWrapper):
    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)
        self.commented = 0
    def write(self, s):
        if s.startswith('#'):
            self.commented += 1
            super().write(s)

buffered = open(name, 'wb')
textio = MyTextIO(buffered, encoding='utf-8')
textio.write('line 1')
textio.write('# line 2')
textio.close()
print(textio.commented)

HTH,
Ian



More information about the Python-list mailing list