New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
unnecessary copying of memoryview in gzip.GzipFile.write? #67876
Comments
I thought I'd go back to work on a test patch for bpo-21560 today, but now I'm puzzled by the explicit handling of memoryviews in gzip.GzipFile.write. def write(self,data):
self._check_closed()
if self.mode != WRITE:
import errno
raise OSError(errno.EBADF, "write() on read-only GzipFile object")
if self.fileobj is None:
raise ValueError("write() on closed GzipFile object")
# Convert data type if called by io.BufferedWriter.
if isinstance(data, memoryview):
data = data.tobytes()
if len(data) > 0:
self.size = self.size + len(data)
self.crc = zlib.crc32(data, self.crc) & 0xffffffff
self.fileobj.write( self.compress.compress(data) )
self.offset += len(data)
return len(data) So for some reason, when it gets passed data as a meoryview it will first copy its content to a bytes object and I do not understand why. Did I miss something about the importance of the tobytes conversion ? |
The patch looks good to be me, but it lacks an unit test. Can you please add a simple unit test to ensure that it's possible to memoryview to write(), and that the result is correct? (ex: uncompress and ensure that you get the same content) |
Better way is data = data.cast('B'). |
Why is this cast required? Can you please elaborate? If some memoryview must be rejected, again, we need more unit tests. |
Here is a patch with memoryview tests. |
@serhiy: |
memoryview is converted to bytes because len() for memoryview returns a size of first dimension (a number of items for one-dimension view), not a number of bytes. >>> m = memoryview(array.array('I', [1, 2, 3]))
>>> len(m)
3
>>> len(m.tobytes())
12
>>> len(m.cast('B'))
12 |
Right, I was aware of this. But are you saying that my proposed solution (using memoryview.nbytes) is wrong ? If so, then cast is certainly an option and should still outperform tobytes. |
It's more convinient to have a single patch with both changes. |
You patch is correct Wolfgang, but with cast('B') the patch would be smaller (no need to replace len(data) to nbytes). While we are here, it is possible to add the support of general byte-like objects. if not isinstance(data, bytes):
data = memoryview(data).cast('B') isinstance() check is just for optimization, it can be omitted if doesn't affect a performance. |
With and without the patch, write() accepts bytes, bytearray and memoryview. Which other byte-like types do you know? writeframesraw() method of aifc, sunau and wave modules use this pattern: if not isinstance(data, (bytes, bytearray)):
data = memoryview(data).cast('B') We can maybe reuse it in gzip module? |
The "bytes-like object" term is used as an alias of "an instance of type that
Yes, I wrote this code, if I remember correct. |
I would say that the current patch looks correct enough, in that it would still get the correct lengths when a memoryview() object is passed in. The zlib module’s crc32() function and compress() method already seem to support arbitrary bytes-like objects. But to make GzipFile.write() also accept arbitrary bytes-like objects, you probably only need to change the code calculating the length to something like: with memoryview(data) as view:
length = view.nbytes # Go on to call compress(data) and crc32(data) |
Thanks everyone for the lively discussion ! I like Serhiy's idea of making write work with arbitrary objects supporting the buffer protocol. In fact, I noticed before that GzipFile.write misbehaves with array.array input. It pretends to accept that, but it'll use len(data) for calculating the zip file metadata so reading from the file will later fail. I was assuming then that fixing that would be too complicated for a rather exotic usecase, but now that I see how simple it really is I think it should be done. As for the concrete implementation, I guess an isinstance(data, bytes) check to speed up treatment of the most common input is a good idea, but I am not convinced that bytearray deserves the same attention. Regarding memoryview.cast('B') vs memoryview.nbytes, I see Serhiy's point of keeping the patch size smaller. Personally though, I find use of nbytes much more self-explanatory than cast('B') the purpose of which was not immediately obvious to me. So I would opt for better readability of the final code rather than optimizing patch size, but I would be ok with either solution since it is not about the essence of the patch anyway. Finally, the bug I report in bpo-21560 would be fixed as a side-effect of this patch here (because trying to get a memoryview from str would throw an early TypeError). Still, I think it would be a good idea to try to write to the wrapped fileobj *before* updating self.size and self.crc to be protected from unforeseen errors. So maybe we could include that change in the patch here ? With all that the final code section could look like this: if isinstance(data, bytes):
length = len(data)
else:
data = memoryview(data)
length = data.nbytes
if length > 0:
self.fileobj.write( self.compress.compress(data) )
self.size = self.size + length
self.crc = zlib.crc32(data, self.crc) & 0xffffffff
self.offset += length
return length One remaining detail then would be whether one would want to catch the TypeError possibly raised by the memoryview constructor to turn it into something less confusing (after all many users will not know what a memoryview has to do with all this). The above code would throw (with str input for example): Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/home/wolma/gzip-bug/Lib/gzip.py", line 340, in write
data = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'str' Maybe, this could be turned into: TypeError: must be bytes / bytes-like object, not 'str' ? to be consistent with the corresponding error in 'wt' mode ? Let me know which of the above options you favour and I'll provide a new patch. |
ok, I've prepared a patch including tests based on my last suggestion, which I think is ready for getting reviewed. |
Here is a revised version of my patch addressing Serhiy's review comments. |
In general the patch LGTM. |
New changeset 4dc69e5124f8 by Serhiy Storchaka in branch 'default': |
I think there's a behavior change: Before you could gzip non-contiguous |
Could you provide an example? |
Sure: import gzip
x = memoryview(b'x' * 10)
y = x[::-1]
with gzip.GzipFile("xxxxx", 'w') as f:
f.write(y) |
ouch. haven't thought of this. OTOH, just plain io with your example: with open('xy', 'wb') as f:
f.write(y) Traceback (most recent call last):
File "<pyshell#29>", line 2, in <module>
f.write(y)
BufferError: memoryview: underlying buffer is not C-contiguous fails too and after all that's not too surprising. In a sense, the old behavior was an artefact of silently copying the memoryview to bytes. You never used it *directly*. |
to preserve compatibility: there is the memoryview.c_contiguous flag. Maybe we should just check it and if it is False fall back to the old copying behavior ? |
something like: def write(self,data):
self._check_closed()
if self.mode != WRITE:
import errno
raise OSError(errno.EBADF, "write() on read-only GzipFile object")
if self.fileobj is None:
raise ValueError("write() on closed GzipFile object")
if isinstance(data, bytes):
length = len(data)
elif isinstance(data, memoryview) and not data.c_contiguous:
data = data.tobytes()
length = len(data)
else:
# accept any data that supports the buffer protocol
data = memoryview(data)
length = data.nbytes
if length > 0:
self.fileobj.write(self.compress.compress(data))
self.size += length
self.crc = zlib.crc32(data, self.crc) & 0xffffffff
self.offset += length
return length |
Here is a patch that restores support on non-contiguous memoryviews. It would be better to drop support of non-contiguous data, because it worked |
It likely wasn't intentional, but tobytes() *is* used to serialize Since the gzip docs don't help much, I guess the new behavior is |
I just see that non-contiguous arrays didn't work in 2.7 either, |
Serhiy: I think I saw that you committed this also to the 2.7 branch, but that would not work since memoryviews do not have the nbytes attribute (they do not seem to have cast either). One would have to calculate the length instead from other properties. If I'm mistaken, then sorry for the noise. |
OK, so left it as is if nobody complains. |
I see now that it is just bpo-21560 that went into 2.7 and that's fine. |
I committed only working tests and a fix from bpo-21560. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: