Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should one use BytesIO .getvalue() instead of .getbuffer()?

According to the BytesIO docs:

getbuffer()

Return a readable and writable view over the contents of the buffer without copying them. Also, mutating the view will transparently update the contents of the buffer:

getvalue()

Return bytes containing the entire contents of the buffer.

So it seems as if getbuffer is more complicated. But if you don't need a writable view? Would you then simply use getvalue? What are the trade-offs?

Minimal Example

In this example, it seems as if they do exactly the same:

# Create an example
from io import BytesIO
bytesio_object = BytesIO(b"Hello World!")

# Write the stuff
with open("output.txt", "wb") as f:
    f.write(bytesio_object.getbuffer())
like image 639
Martin Thoma Avatar asked Apr 20 '20 09:04

Martin Thoma


People also ask

What does Getvalue do in Python?

getvalue() just returns the entire contents of the stream regardless of current position.

What is BytesIO in Python?

StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.


1 Answers

Using getbuffer() is better, because, if you have really BIG data, copying them may take a long time. And (from PEP 20):

Explicit is better than implicit.
But value is undefined - it may be str or bytes. Buffer is always bytes.
like image 103
Vad Sim Avatar answered Oct 13 '22 13:10

Vad Sim