Sunday, January 31, 2010

Flush to the Rescue, None is not zero

Well, that was quick.  (See my previous blog post about socket.makefile() in Python 3.1.1). I was sent a message to try the flush() method on the file object after attempting to write to it.  Indeed that works for both the binary io.BufferedWriter and text based io.TextIOWraper.  We usually think about using a I/O flush() method to switch between writing and reading operations, but here it is needed just to force the message to be sent instead of being held up in the buffer.

So the only question remaining is on the default value for the buffering parameter to makefile().  The following results in a buffered objects, which is what one might expect:

fd = s.makefile('w') -> buffered io.TextIOWrapper
fd = s.makefile('wb') -> buffered io.BufferedWriter

However, the default value for buffering is None, so the above two statements are equivalent to the following two, which one might think would would return an unbuffered object rather than the buffered objects returned just as above.

fd = s.makefile('w', buffering = None) -> buffered io.TextIOWrapper
fd = s.makefile('wb', buffering = None) -> buffered io.BufferedWriter

Perhaps it would be more obvious to list the default value of buffering as True, with maybe another parameter for the default buffer size.  I won't hold my breath for that change.   I'd be happy to see the documentation updated to reflect that buffering must be set to zero (buffering = 0), to get an unbuffered file object from socket.makefile()

No comments:

Post a Comment