[Python-ideas] struct.unpack should support open files

Andrew Svetlov andrew.svetlov at gmail.com
Mon Dec 24 08:01:07 EST 2018

Handling files overcomplicates both implementation and mental space for API

Files can be opened in text mode, what to do in this case? What
exception should be raised?
How to handle OS errors?

On Mon, Dec 24, 2018 at 1:11 PM Drew Warwick <dwarwick96 at gmail.com> wrote:

> 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.
>> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/

Andrew Svetlov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20181224/372e4480/attachment-0001.html>

More information about the Python-ideas mailing list