[Python-ideas] struct.unpack should support open files
Drew Warwick
dwarwick96 at gmail.com
Mon Dec 24 06:11:01 EST 2018
The struct unpack API is inconvenient to use with files. I must do:
struct.unpack(fmt, file.read(struct.calcsize(fmt))
every time I want to read a struct from the file. I ended up having to
create a utility function for this due to how frequently I was using
struct.unpack with files:
def unpackStruct(fmt, frm):
if isinstance(frm, io.IOBase):
return struct.unpack(fmt, frm.read(struct.calcsize(fmt)))
else:
return struct.unpack(fmt, frm)
This seems like something that should be built into the default
implementation -- struct.unpack already has all the information it needs
with just the struct format and open binary file. Current behavior is an
error since struct.unpack only supports bytes-like objects, so this should
be backwards compatible except in the case where a developer is relying on
that to error in a try block instead of verifying the buffer type
beforehand.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20181224/7cd41c34/attachment.html>
More information about the Python-ideas
mailing list