[Python-Dev] Possible py3k io wierdness

Brian Quinlan brian at sweetapp.com
Mon Apr 6 08:51:21 CEST 2009


James Y Knight wrote:
> 
> On Apr 5, 2009, at 6:29 AM, Antoine Pitrou wrote:
> 
>> Brian Quinlan <brian <at> sweetapp.com> writes:
>>>
>>> I don't see why this is helpful. Could you explain why
>>> _RawIOBase.close() calling self.flush() is useful?
>>
>> I could not explain it for sure since I didn't write the Python version.
>> I suppose it's so that people who only override flush() automatically 
>> get the
>> flush-on-close behaviour.
> 
> It seems that a separate method "_internal_close" should've been defined 
> to do the actual closing of the file, and the close() method should've 
> been defined on the base class as "self.flush(); self._internal_close()" 
> and never overridden.

Are you imagining something like this?

class RawIOBase(object):
   def flush(self): pass
   def _internal_close(self): pass
   def close(self):
     self.flush()
     self._internal_close()


class FileIO(RawIOBase):
   def _internal_close(self):
     # Do close
     super()._internal_close()

class SomeSubclass(FileIO):
   def flush(self):
     # Do flush
     super().flush()

   def _internal_close(self):
     # Do close
     super()._internal_close()

That looks pretty good. RawIOBase.close acts as the controller and 
.flush() calls move up the class hierarchy.

The downsides that I see:
- you need the cooperation of your subclasses i.e. they must call
   super().flush() in .flush() to get correct close behavior (and this
   represents a backwards-incompatible semantic change)
- there is also going to be some extra method calls

Another approach is to get every subclass to deal with their own close 
semantics i.e.

class RawIOBase(object):
   def flush(self): pass
   def close(self): pass

class FileIO(RawIOBase):
    def close(self):
      # Do close
      super().close()

class SomeSubclass(FileIO):
   def _flush_internal(self):
     # Do flush

   def flush(self):
     self._flush_internal()
     super().flush()

   def close(self):
     FileIO._flush_internal(self)
     # Do close
     super().close()

I was thinking about this approach when I wrote this patch:
http://bugs.python.org/file13620/remove_flush.diff

But I think I like your way better. Let me play with it a bit.

Cheers,
Brian


More information about the Python-Dev mailing list