[Python] io.BytesIO does not have a peek method. What alternative solution can be used?

Discussão em 'Python' iniciado por Stack, Dezembro 1, 2024.

  1. Stack

    Stack Membro Participativo

    The io.BytesIO object in Python does not have a peek method.

    There is actually an open PR related to this, however it has been open since 2022.


    The author commented suggesting that they had come to the conclusion that there was no peek method by design.

    In either case, what alternative can be used to obtain this functionality?

    The author of the same PR suggested using a io.BufferedReader object instead. However, this seems like a strange choice because it is asymmetrical. In other words, it does not support both the reading and writing type functions.

    There is another class, io.BufferedRandom, which appears to inherit from both io.BufferedReader and io.BufferedWriter.

    I thought this could be a suitable alternative, but I can't figure out how it is intended to be used.

    If I try to create an empty io.BufferedRandom, I get an error missing required argument 'raw'.

    buffer = io.BufferedRandom()


    So I'm unsure as to what I should do instead.

    It could be that I am looking in completely the wrong place and the wrong library.

    I want some kind of buffer object which I can read, write and peek. The intended use case is to make reading from a socket simpler. Since calling recv on a socket can return any number of bytes, my idea is to use a buffer to stash the recieved data until there is enough available to interpret what has been received.

    Continue reading...

Compartilhe esta Página