On 23 January 2014 11:30, Victor Stinner <[email protected]> wrote:

> Hi,
>
> I found the StreamReader.readexactly(n) function which has a strange
> behaviour. It reads exactly n bytes... but it returns less if the end
> of stream is reached.
>
> Why not raising an exception? When I use such function, I expected to
> get... exactly... n bytes, not "almost" n bytes :-)
>
> It would be annoying to write:
>
>    data = reader.readexactly(n)
>    if len(data) != n: ...
>
> For each call to readexactly(). I prefer to write optimistic code and
> maybe catch an exception if needed.
>
> We may raise an exception with the incomplete data. For example,
> subprocess.check_call() raises an exception which contains the return
> code, the command and the output. The io module uses a BlockingIOError
> which contains the number of written bytes.
>
> The code even contains this comment:
>
>     # TODO: Raise EOFError if we break before n == 0?  (That would
>     # be a change in specification, but I've always had to add an
>     # explicit size check to the caller.)
>
> I opened an issue with a patch to raise an IncompleteReadError which
> inherits from EOFError and contains the partial data:
> http://code.google.com/p/tulip/issues/detail?id=111
>
>
+1

I think reader.readexactly(n) is meant to be called in the context of a
protocol where less than n bytes would be a protocol violation, anyway.
 Usually, protocol violations are rare (are really exceptional) and can be
handled in a coarse-grained try: .. except: .. block.


-- 
Gustavo J. A. M. Carneiro
Gambit Research LLC
"The universe is always one step beyond logic." -- Frank Herbert

Reply via email to