[Python-Dev] BufferedReader.peek() ignores its argument (original) (raw)

Alexandre Vassalotti alexandre at peadrop.com
Sun Apr 5 08:07:29 CEST 2009


On Sat, Apr 4, 2009 at 9:03 PM, Antoine Pitrou <solipsis at pitrou.net> wrote:

Hello,

Currently, BufferedReader.peek() ignores its argument and can return more or less than the number of bytes requested by the user. This is how it was implemented in the Python version, and we've reflected this in the C version. It seems a bit strange and unhelpful though. Should we change the implementation so that the argument to peek() becomes the upper bound to the number of bytes returned?

I am not sure if this is a good idea. Currently, the argument of peek() is documented as a lower bound that cannot exceed the size of the buffer:

    Returns buffered bytes without advancing the position.

    The argument indicates a desired minimal number of bytes; we
    do at most one raw read to satisfy it.  We never return more
    than self.buffer_size.

Changing the meaning of peek() now could introduce at least some confusion and maybe also bugs. And personally, I like the current behavior, since it guarantees that peek() won't return an empty string unless you reached the end-of-file. Plus, it is fairly easy to cap the number of bytes returned by doing f.peek()[:upper_bound].

-- Alexandre



More information about the Python-Dev mailing list