I would like to implement a class which inherits from RawIOBase. I'm struggling to implement the readinto method. Basically, I don't know how to alter the content of the bytearray object passed as a parameter.
I've tried following (naive) approach:
def readinto(self, b):
data = self.read(len(b))
b = data
return len(data)
But this, as I suspect, will assign new bytearray
object to local variable b and it does not change content of the original bytearray
.
Description Python file method read () reads at most size bytes from the file. If the read hits EOF before obtaining size bytes, then it reads only available bytes.
The default implementation defers to readall () and readinto (). Read and return all the bytes from the stream until EOF, using multiple calls to the stream if necessary. Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. For example, b might be a bytearray .
If the read hits EOF before obtaining size bytes, then it reads only available bytes. size − This is the number of bytes to be read from the file. This method returns the bytes read in string. The following example shows the usage of read () method.
Implement required methods. On the menu, click Ctrl+I. Alternatively, you can right-click anywhere in the class file, then click Generate Alt+Insert, and select Implement methods. Select the methods to implement. If necessary, select the Copy JavaDoc checkbox to insert JavaDoc comments for the implemented interface or abstract class.
from the docs of RawIOBase.readinto
:
Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. If the object is in non-blocking mode and no bytes are available, None is returned.
its a bit confusing but you need to write into the bytes-like object b
(not read)
import io
class MyIO(io.RawIOBase):
def readinto(self, b):
msg = b'hello'
b[:len(msg)] = msg
return len(msg)
i = MyIO()
buf = bytearray()
i.readinto(buf)
print(buf)
Take a look at CPython implementation of BytesIO.readinto
.
basically its does memcpy from the object's buffer to the function input buffer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With