[Python-Dev] an idea for improving struct.unpack api (original) (raw)

Paul Moore p.f.moore at gmail.com
Sat Jan 8 12:09:47 CET 2005


On Fri, 7 Jan 2005 19:40:18 -0800 (PST), Ilya Sandler <ilya at bluefir.net> wrote:

Eg. I just looked at xdrlib.py code and it seems that almost every invocation of struct.unpack would shrink from 3 lines to 1 line of code

_( i = self.pos _self.pos = j = i+4 _data = self.buf[i:j] return struct.unpack('>l', data)[0] would become: _return struct.unpack('>l', self._buf, self.pos)[0] )

FWIW, I could read and understand your original code without any problems, whereas in the second version I would completely miss the fact that self.__pos is updated, precisely because mutating arguments are very rare in Python functions.

OTOH, Nick's idea of returning a tuple with the new offset might make your example shorter without sacrificing readability:

result, newpos = struct.unpack('>l', self.__buf, self.__pos)
self.__pos = newpos # retained "newpos" for readability...
return result

A third possibility - rather than "magically" adding an additional return value because you supply a position, you could have a "where am I?" format symbol (say & by analogy with the C "address of" operator). Then you'd say

result, newpos = struct.unpack('>l&', self.__buf, self.__pos)

Please be aware, I don't have a need myself for this feature - my interest is as a potential reader of others' code...

Paul.



More information about the Python-Dev mailing list